1

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);
conor909
  • 1,475
  • 14
  • 29
  • have you confirmed that the Ajax call is successful? like, `console.log(data)` right before `myVar = data;`? – vch Aug 16 '14 at 16:35
  • Yes data retrieves an object with a responseJSON – conor909 Aug 16 '14 at 16:52
  • have the console.log inside the done function and then check that myVar is getting filled our not – V31 Aug 16 '14 at 16:55
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Felix Kling Aug 16 '14 at 17:12

1 Answers1

3

$.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.

Community
  • 1
  • 1
Rhumborl
  • 16,349
  • 4
  • 39
  • 45