1

In the following code, I want the alerts to come in order (1st call followed by the second), but it keeps coming the other way around. This is causing some variables to become undefined. What is the order of execution when having multiple ajax queries in the same code? How can I change the order of the alerts?

$(document).ready(function () {

  function get_det() {
    $.ajax({
      url: "aa.php",
      type: "POST",
      success: function (result) {
        alert("1st call");
      }
    });
  }

  $.ajax({
    type: "POST",
    contentType: "application/json",
    url: "dd.php",
    success: function (result) {
      initializeMap();
    }
  });


  function initializeMap() {
    //other code
    calculateAndDisplayRoute();
    //other code

    function calculateAndDisplayRoute() {
      //other code
      get_det();
      alert("2nd call");
      //other code
    }

  }

});

3 Answers 3

2

Ajax is by default Asynchronous meaning there will be no wait for response. That is why your 2nd call is calling before ajax request. You can make ajax Syncronuous by setting async: false. Not recommended as it could cause browser hanging.

For Asynchronous process you can use callback function which only call when your request is completed.(Recommended)

In javascript you can do like this(For your code):

function get_det(callback) {//Your asynchronous request.  
    $.ajax({
      url: "aa.php",
      type: "POST",
      success: function (result) {
        alert("1st call");
        callback();//invoke when get response 
      }
    });
  }

call like this:

get_det(secondFunction);//calling with callback function

function secondFunction()//your callback function
{
 alert("2nd Call");
}
Sign up to request clarification or add additional context in comments.

4 Comments

Yours answer is correct, but i advise to use call() method instead.
Thanks for your advise :) If possible please edit this as i haven't use call() .I understand what it is but not sure where to call and where to not.
Thanks, using async:false worked for me. You are god! Thanks for putting me in the right direction, learnt about async and sync requests in javascript. Didn't know about that before.
@NisalUpendra To be fair, making ajax request synchronous is possible, but should be used with caution. When the process is made synchronous, it will cause the browser hanging if the data transfer takes a while. I would recommend to use Anand's solution to get your order of alerts intact. Nobody wants to face a hanging browser.
2

The difference in behavior is due to async nature of ajax calls. In your case, you want to perform some code once the call has executed, hence, you need to use callback functions.

Update your code to following

function get_det(callback) {
    $.ajax({
      url: "aa.php",
      type: "POST",
      success: function (result) {
        alert("1st call");
        if(callback) {
          callback();
        }
      }
    });
  }

 function calculateAndDisplayRoute() {
      //other code
      get_det(function() { 
         /* this is the place where you need to put code 
          * that needs to be executed after the ajax has been executed */
         alert("2nd call");
      });
    }

13 Comments

@NisalUpendra - This will not work as you have not passed callback function. A simpler change will be getwypts(function(){alert("hello");});
@NisalUpendra - In place of alert move your code that you have written after calling getwypts function. Freezing effect becomes more visible when code is deployed on production or the call takes a lot of time.
And voila! she works. Hat's off @nikhil. Thank you soo much. I accepted your answer. Great if you could update your answer with this
@NisalUpendra - Anand has a better explanation and hence, it is my humble request please stick to your original accepted answer. My objective was to try and make things work for you as it should be. Also, please let me know what update you want w.r.t. my answer. I will do that.
As you wish. I reset it. I'm asking you to point out that code executed after the function can be included in the callback.
|
0

I suggest chaining the promises that $.ajax returns.

$(document).ready(function () {

  function get_det() {
    return $.ajax({
      url: "aa.php",
      type: "POST"
    }).then(function(result) {
      // Do some stuff - you can even modify the result!
      // Return the result to the next "then".
      return result;
    })
  }

  // Named after the php script you're hitting.
  function dd() {
    // Return the promise from Ajax so we can chain!
    return $.ajax({
      type: "POST",
      contentType: "application/json",
      url: "dd.php"
    });
  }

  function initializeMap() {
    // Do stuff before call
    return get_det().then(function(getDetResult) {
      // Do stuff after AJAX returns..
      return {
        getDetResult: getDetResult,
        mapInitialized: true
      };
    });
  }

  // use it!
  dd().then(function(result) {
    alert('1st call');
    // Pass result from dd to initializeMap.
    return initializeMap(result);
  }).then(function(initMapResult) {
    alert('2nd call', initMapResult.mapInitialized);
  });

});

2 Comments

Thanks for adding this answer. I wasn't aware (or heard) of chaining promises in jquery till now. i will try this out too.
@NisalUpendra It's extremely flexible - asynchronous stuff becomes super simple.

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.