0

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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');
}):

Comments

0

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...
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.