2.6.32
2.6.32

Reputation: 35

Does a ajax callback function guarantee synchronous execution?

For example:

ajaxCall() {
    $.ajax({
      ...
      ...
      success: function(response) {
        event2();
      }
    });
}

If we have a call like:

event1();
ajaxCall();
event3();

Would it be always guaranteed that the order of execution of events be event1() then event2() and event3() without setting the async flag ?

Upvotes: 0

Views: 123

Answers (3)

Quentin
Quentin

Reputation: 943651

No.

The callback function will fire when the event that triggers it (i.e. the HTTP response) happens.

A function you call immediately after you assign the callback will still be called immediately.

The order of execution will still be:

event1();
ajaxCall();
    $.ajax();
event3();
success();
    event2();

Upvotes: 0

jdabrowski
jdabrowski

Reputation: 1975

AJAX is Asynchronous JAX :) There's your answer.

If you want to make a synchronous call, you need to set the async: false flag. But then the success callback won't be called at all and you would need to put the event2(); line just below the $.ajax call.

Also see Mike C's answer. The synchronous calls are deprecated.

Upvotes: 3

Mike Cluck
Mike Cluck

Reputation: 32511

In general, you're right if you set async to false. However, synchronous AJAX has been deprecated and jQuery officially dropped support for it after v1.8.

So I would suggest you avoid trying to use synchronous AJAX requests.

Upvotes: 1

Related Questions