1

This is more of a basic JQuery/Javascript question: How do I get data out of the getJSON function?

The following code works great until the function ends. I have several getJSON that will need to run one-after-the-other and I would like to avoid nesting them if I can:

//Using the Web API to pull all the information out for the current ORG ID
$.getJSON('http://localhost:8081/dhis/api/organisationUnits/' + vuCurrentFacilityID + '.json', function (data) {
  //alert(data.message);
  console.log(data);
  vuCurrentFacilityName = data.name;
  vuParentFacilityID = data.parent.name;
});

alert(vuCurrentFacilityName); //does not work

What Gotcha* am I missing? This question is very similar to the following.

Community
  • 1
  • 1
Timothy Harding
  • 277
  • 2
  • 12
  • http://stackoverflow.com/questions/6922237/scope-for-getjson-in-jquery?rq=1 Solved my problem, doesn't look like it is a good idea to get data out of getJSON. Nesting it is then! – Timothy Harding May 23 '14 at 00:18

1 Answers1

1

if you call $.getJSON() you are entering an asynchronous context, and everything after it gets executed immediately. So your alert is called before the server responds.

use deferreds instead

var promise = $.getJSON( ... );

promise.done(function() {
    alert("yeah");
});
Luke
  • 8,235
  • 3
  • 22
  • 36
  • Why not just move the alert inside the callback with the console.log and all that? You must have submitted your answer 2 seconds before it was locked. I didn't make it. :( – DutGRIFF May 23 '14 at 00:22
  • i think `deferreds` are cleaner and you can attach the `done` handler as often you like. even if the getJSON is already finished, you can further on attach a `done` callback to it, and it will be called immediately as the promise is already defined. – Luke May 23 '14 at 00:24
  • +1 That is pretty cool to note. It could be very helpful in other situations. Thanks. http://api.jquery.com/category/deferred-object/ – DutGRIFF May 23 '14 at 00:27