Brian
Brian

Reputation: 27392

Make sure ajax function finishes before 2nd non-ajax function fires

Similar to the question I just asked,

If I call an ajax function in jQuery and then a non ajax function how can I prevent the non-ajax function from firing until after the first ajax callback function has completed. Will declaring async: false in the first ajax function be enough?

Upvotes: 2

Views: 454

Answers (3)

Usman Afzal
Usman Afzal

Reputation: 466

You can use callback functions like this:

$("#btnSample").on("click", function (e) {

 $.ajax({
    url: 'some_url',
    type: "GET",
    async: true,
    cache: false,
    dataType: "JSON",
    data: { 
      "p1": v1, 
      "p2": v2
    },
    success: function(result) {
      //call you second function here!
    }  
  }
});

});

Upvotes: 0

cletus
cletus

Reputation: 625007

If you're talking about this:

$.ajax({...});
someFunction();

where someFunction() won't occur until the AJAX call completes then you have three options:

  1. Make the AJAX call async: false. Don't do this. It'll make your page unresponsive;
  2. Put someFunction() in the complete/success/error callbacks of the AJAX call. This is the recommended approach; or
  3. Use aplugin to manage a request queue eg Ajax Queue.

The first A in AJAX stands for "asynchronous". You just need to get used to the fact that these calls are asynchronous and stop trying to force a synchronous programming model on top of them. Adapt to the new programming model.

Upvotes: 4

Victor Nicollet
Victor Nicollet

Reputation: 24577

jQuery AJAX functions let you provide a callback that is only called after the request is finished. Call your non-ajax function as part of that callback.

Upvotes: 1

Related Questions