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!
Asynchronicity. The line
alert(possibleMatches.length);executes before the success callback for$.getJSON()executes.So, to have your alert report accurately, just move it.
Remember, the first A in AJAX stands for “Asynchronous”