Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can i make make a variable in a javascript and give it a value from an json array?

The array is sent from a php script and looks like this:

php

$stat = array("v1" => "$v1", "v2" => "$v2", "v3" => "$v3",
"v4" => "$v4", "v5" => "$v5", "pump" => "$pump", "flow" => "$flow");
echo json_encode(($stat));

html/javascript

$.ajaxSetup({ cache: false });
setInterval(function(){
$.getJSON('statusdata.php',function(data) {
$.each(data, function(key, val) {

// I try to do something like this..
var v1 = key[1];
var v2 = key[2];
and so on..

Then i want to use a variable to alert a popup-window with some kind of warning.

Someting like:

if (v1 == 1){
run the popup function!
}

Can anyone help me?

share|improve this question
 
It seems like you don't know how to access object properties / array elements. I recommend to read the MDN JavaScript guide: developer.mozilla.org/en-US/docs/JavaScript/Guide/…. Maybe you also have to read about how $.each works: api.jquery.com/jQuery.each. FYI, data will be an object, so key will be the name of the property (e.g. 'v1', 'pump') and val will be the value of that property. –  Felix Kling Apr 7 '13 at 17:45
add comment

1 Answer

You're using $.each wrong. If you're going to be assigning from data to a set up regular variables you need to do them all individually, not inside a loop.

$.getJSON('statusdata.php',function(data) {
  v1 = data["v1"];
  v2 = data["v2"];
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.