Reputation: 659
So I'm trying to assign data from JSON to a global variable to use it multiple times later, but I get this problem. First alert passes ok, but for the second one I get cannot read propery 4 of undefined.
var refference=[]
$.getJSON('letters.json', function(data) {
refference=data.letters
alert(refference[1][4])
})
alert(refference[1][4])
Thanks!
Upvotes: 2
Views: 617
Reputation: 1352
As Kevin B said, the alert is firing before the ajax call is complete. You'd have to put the second alert (or any other function) in the success callback of the ajax request to ensure that it fires after the data is completely loaded.
something like:
$.getJSON('letters.json', function(data) {
refference=data.letters;
alert(refference[1][4]);
}).success(function(){
alert(refference[1][4]);
});
Here's a working jsFiddle example using a JSON webservice
Upvotes: 1
Reputation: 7466
The second alert(refference[1][4])
will give you an error because at that point in time, the $.getJSON()
request has not returned yet. So refference
object is still []
, therefore property 4 is undefined.
Upvotes: 5