0

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?

Seneca
  • 2,392
  • 2
  • 18
  • 33
  • _"when I later call persons.length"_ - I'm guessing scope or async issue. Can you show us more context? – Jason P Jan 31 '14 at 19:11
  • When are you trying to call `persons.length`? `$.get` is asynchronous, so it may not be done yet. – gen_Eric Jan 31 '14 at 19:11
  • 1
    See "[How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call)" The difference is that `$.get()` is asynchronous, so `data` and all of the `Person`s created from it are available *later*, when the callback is called sometime after the surrounding code has continued to execute. – Jonathan Lonowski Jan 31 '14 at 19:11
  • 1
    @JonathanLonowski That may be relevant, however, it doesn't explain the error that is occurring. The error states that `persons` is undefined, but it is clearly defined in the code he provided. – Kevin B Jan 31 '14 at 19:14
  • Problem solved! Thank you guys!! Thanks a lot !!! I had a method showResults() that modified my html, solution was to call it inside de $.getJSON() Async issues :D I feel so stupid right now xD – Seneca Jan 31 '14 at 19:17
  • So, post your answer and mark it as accepted. – lshettyl Mar 13 '14 at 10:48

1 Answers1

6

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
Jordan
  • 181
  • 9