$.getJSON
is asynchronous. That is, the code after the call is executed while $.getJSON
fetches and parses the data and calls your callback.
So, given this:
a();
$.getJSON("url", function() {
b();
});
c();
The order of the calls of a
, b
, and c
may be either a b c
(what you want, in this case) or a c b
(more likely to actually happen).
The solution?
Synchronous XHR requests
Make the request synchronous instead of asynchronous:
a();
$.ajax({
async: false,
url: "url",
success: function() {
b();
}
});
c();
Restructure code
Move the call to c
after the call to b
:
a();
$.getJSON("url", function() {
b();
c();
});