1
{
   "Adam":{
      "Math":"93",
      "Science":"96",
      "Email":"[email protected]",
      "City":"NY"
   },
   "Tom":{
      "Math":"65",
      "Science":"56",
      "Email":"[email protected]",
      "City":"LA"
   },
   "Joe":{
      "Math":"74",
      "Science":"83",
      "Email":"[email protected]",
      "City":"Washington"
   }
}

Above is the JSON content present at the http: //ActualUrl/path.json

I am accessing the JSON file and filling the two arrays with name and marks in science with the code below.

     var names=[];
     var marks=[];
    $.getJSON("http://path.json",function(data){               
                $.each(data, function(key, val) {   
                     names.push(key);
                    // I placed alert the check the value key.
            marks.push(parseInt(val.Science));                  
                    });
                });
    alert(names.toString()); // names is found blank
    alert(marks.toString()); 

When I check the array at the end. Array is found blank. Why this wrong behaviour with getJSON ? I placed alert in the each and check the value. It returns correct value.

2
  • what if you alert(names) and alert(marks) only? without using toString() function Commented Jan 16, 2012 at 12:18
  • Array can not be printed like alert(names) Commented Jan 16, 2012 at 12:25

3 Answers 3

4

$.getJSON fires off asynchronously, meaning that in most cases it will not have completed by the time you read out your variables. You will need to restructure your solution such that you do the thing you want to do within it's success callback:

$.getJSON("http://path.json", function(data) {
    $.each(data, function(key, val) {
        names.push(key);
        marks.push(parseInt(val.Science));
    });

    // do your thing here.
});
Sign up to request clarification or add additional context in comments.

1 Comment

@karim79, thanks..! I accepted above due to nice explanation :)
2

Primary problem

You are filling your array in the async callback, but alert them right away. So, this is what happens:

  1. You execute ajax call. Request is sent to the server.

  2. You alert values of arrays. They are blank, since the server didn't reply yet.

  3. Server replies, your callback is fired and arrays are filled. Too late.

Solution:

Put alert logic to the callback.

Other notes

jQuery.each is for iterating collections. You, on the other hand, have an object (or dictionary).

Try this code:

for(key in data) {
  names.push(key);
  var val = data[key];
  marks.push(parseInt(val.Science));                  
}

for ... in ... construct iterates object properties, which is what you want.

5 Comments

Don't forget to check data.hasOwnProperty(key) before adding anything to the arrays. See developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
Actually that wasn't the real problem here. Async callback was :-)
@SergioTulentsev, With your code, marks.toString() returns proper output, but names.toString() is blank. Why so ?
@Umesh: check for typos. Works on my machine.
@SergioTulentsev, thanks!! it works but server response is slow. may be it doesn't work sometimes :)
0

$.each Description: Iterate over a jQuery object, executing a function for each matched element. (from: http://api.jquery.com/each/ )

The returned JSON is not a jQuery object, just a plain JavaScript object. Use foreach(key in data) instead.

Oh and move the alert() inside the callback function :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.