Reputation: 7535
I have code that looks like this:
jQuery.getJSON( "url/to/some/script.php", function( data ) {
var test = data.someValue;
console.log('This message should occur first');
});
console.log('this message should occur second');
// do things with data retrived above...
What's happening is, that first console.log
is executing AFTER the second one. I suppose because it's taking time to make the Ajax request, but I didn't realize it would continue moving down the script without finishing. As such, variables that result from the AJAX request are 'undefined' when I try and use them in the code directly following this.
What might be the best way to deal with such a situation?
Upvotes: 0
Views: 598
Reputation: 97
you could use jquery promises http://api.jquery.com/promise/ to help with asynchronous javascript
$.getJSON("url/to/some/script.php").success(function(data) {
var test = data.someValue;
console.log('This message should occur first');
}).done(function() {
console.log('this message should occur second');
// do things with data retrived above...
});
Upvotes: 0
Reputation: 765
Use the Promise interface which allows jQuery's Ajax methods like jQuery.getJSON() to chain one or multiple callbacks
jQuery.getJSON( "url/to/some/script.php", function( data ) {
var test = data.someValue;
console.log('This message should occur first');
}).done(function() {
console.log('this message should occur second');
}):
Upvotes: 1
Reputation: 1593
In so-called asynchronous programming there is only one valid solution: put you code that should be run after Ajax is finished into the function, that is:
jQuery.getJSON( "url/to/some/script.php", function( data ) {
var test = data.someValue;
console.log('This message should occur first');
console.log('this message should occur second');
// And all code that should be run after Ajax should go here
});
In traditional languages (for example, PHP) the next line of code is executed after the previous one. If some line has a long time action (like database or Ajax request), then the program will stop execution until this line will get the result of request.
In asynchronous programming, on the opposite, program will not stop. It remembers that this callback function should be called after the request will be done and continues to run all further lines immediately. So, program does not have to stop and wait. But it means that all your code that need request results should be placed in callback function.
Upvotes: 1