Why does this code always return 0?

     var possibleMatches = new Array();
  $.getJSON('getInformation.php', function(data) {
   $.each(data, function(i){
    possibleMatches.push(data[i]);
   })
  });
  alert(possibleMatches.length);

Though I can move or add "alert(possibleMatches.length);" inside the $.each and it will output the correct number of elements.

I'm just curious as to why it the values aren't going into the array as I expected. I'm sure its a local variable vs. global variable issue, just not sure why.

Basically, what this is trying to do is fill the possibleMatches array with the data results.

thanks!

link|flag

3 Answers

up vote 4 down vote accepted

Asynchronicity. The line alert(possibleMatches.length); executes before the success callback for $.getJSON() executes.

So, to have your alert report accurately, just move it.

var possibleMatches = new Array();
$.getJSON('getInformation.php', function(data) {
  $.each(data, function(i){
    possibleMatches.push(data[i]);
  })

  // To here
  alert(possibleMatches.length);
});
// From here

Remember, the first A in AJAX stands for "Asynchronous"

link|flag
@Peter Bailey - Doh! How did I forget that little (but very important) part! That makes perfect sense! Thanks! – psiko.scweek Mar 9 at 17:10
+1 - I didn't believe Asynchronicity was a word :) – Nick Craver Mar 9 at 17:20

$.getJSON performs an asynchronous call, whose callback is executed on completion of the xmlhttprequest used:

var possibleMatches = new Array(); 
$.getJSON('getInformation.php', function(data) {  // <-- this will run later 
    $.each(data, function(i){ 
        possibleMatches.push(data[i]); 
    }) 
}); 
alert(possibleMatches.length);  // this will call immediately
link|flag

The jetJSON request is asynchronous, it finished after your alert runs. If you want an accruate alert, it should be in your callback for getJSON like this:

  $.getJSON('getInformation.php', function(data) {
   $.each(data, function(i){
    possibleMatches.push(data[i]);
   });
   alert(possibleMatches.length);
  });
link|flag

Your Answer

 
or
never shown

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