Seneca
Seneca

Reputation: 2412

Javascript fetch JSON array

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?

Upvotes: 0

Views: 239

Answers (1)

Jordan
Jordan

Reputation: 181

This is probably an issue with scope. If "var persons" is declared within a function then it is in the function's scope. Double check where it is declared, and from where you are trying to access it.

For further reading see: http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/

Edit: I don't believe the asynchronous call $.getJSON would be the cause of the issue because persons.length would be 0 and persons would not be undefined.

var persons = new Array();
print persons.length; // ==> 0

Upvotes: 6

Related Questions