1

I have a strange bug. When I try to run my code:

var firstJson;
$.getJSON(site_url+"/more/sector_by_city/"+id+"?"+Math.random(), function( json ) { 
    $.each(json, function(key, value) {
        firstJson = 9;  
    });
}); 
alert(firstJson);

The alert I get is: "undefined".

Why did I get this instead of getting 9?

What am I missing here?

(the each loop runs without issue and there are values in the JSON) At the end, 9 changes to some other value.

Thanks

3 Answers 3

6

Async functions my friend. Your alert is being called before your .getJSON request has been finished. You'll need to use a callback function to get the correct alert.

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

Comments

4

Because when you call alert(firstJson) the asynchronous $.getJSON call has not yet completed, so firstJson has no value associated with it. If you move your alert into the $.each function or after the $.each, and at the end of $.getJSON, it will have a value.

Comments

2

The variable doesnt have a value when alert is called. You'll have to wait getJSON is over, using done().

var firstJson;
$.getJSON(site_url+"/more/sector_by_city/"+id+"?"+Math.random(), function( json ) { 
    $.each(json, function(key, value) {
        firstJson = 9;  
    });
}).done(function() {
   alert(firstJson);
});

References:

  1. done()
  2. $.getJSON

Comments

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.