I'm trying to fetch a json-array via ajax. my test.php returns:
[{"name":"James","age":24},{"name":"Peter","age":30}]
my Javascript looks like this:
var persons=new Array();
$.getJSON("../../api/test.php", function(data){
$.each(data, function(index,value){
persons.push(new Person(value.name,value.age));
});
});
Problem is when I later call persons.length, I get Cannot read property 'length' of undefined. When I copy/paste the output of test.php from my browser into a local variable, everything works just fine:
var content=[{"name":"James","age":24},{"name":"Peter","age":30}];
for(var i=0; i<content.length; i++)
persons.push(new Person(content[i].name,content[i].age));
What am I doing wrong?
persons.length?$.getis asynchronous, so it may not be done yet.$.get()is asynchronous, sodataand all of thePersons created from it are available later, when the callback is called sometime after the surrounding code has continued to execute.personsis undefined, but it is clearly defined in the code he provided.