Umesh Patil
Umesh Patil

Reputation: 10685

About getJSON function in jQuery

{
   "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.

Upvotes: 1

Views: 598

Answers (3)

Kosta
Kosta

Reputation: 832

$.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 :)

Upvotes: 0

karim79
karim79

Reputation: 342635

$.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.
});

Upvotes: 4

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

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.

Upvotes: 2

Related Questions