conor909
conor909

Reputation: 1623

Global variable not updating after getJSON is done

After I use the getJSON method I want to update the variable, but it doesnt seem to update from inside the .done() function. The following console log is empty.

var myVar;

$.getJSON("url/path", function(data){
}).done(function(data) { 
          myVar = data; 
      });

console.log(myVar);

Upvotes: 1

Views: 921

Answers (1)

Rhumborl
Rhumborl

Reputation: 16609

$.getJSON is asynchronous, so the console.log call is always going to happen before the request completes and the done function is called.

Look at getJSON Synchronous for doing synchronous ajax calls, although this is an anti--pattern and you should be able to do everything in the callback.

Upvotes: 3

Related Questions