2

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!

1
  • 2
    You can't. Ajax is asynchronous, the alert on the outside will happen long before the ajax completes. learn.jquery.com/ajax/key-concepts "A is for Asynchronous" Commented Mar 18, 2013 at 21:59

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

6 Comments

note, your .done() part is invalid and will still alert undefined or throw an error
yeah, my bad. Should have used 'success. Will update my answer and included a working jsFiddle
No, success is depreciated. .done() was correct, but .done(alert(...)) is wrong, so is .success({...})
Are you sure that "success" is depreciated for getJSON? because according to the jquery API it's not. success({...}) also works fine in the example I posted. (or at least it did until the web service's API's demo limit was exceeded)
I see what you're saying about success({...}) I fixed that in my fiddle (added function() )but hadn't pasted that into the answer above.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.