3

I have been working with AJAX for a while now, but in limited and simple ways. I use JQuery

Currently I am debugging a web application. The client side code uses JavaScript and JQuery. I noticed that in this application it is possible to have multiple AJAX requests sent out at the same time (one right after the other). My concern is that because AJAX is asynchronous that the AJAX request might not be completed in the correct order. I was wondering if the proper AJAX callbacks will be executed regardless of witch response is returns first or the call back functions are executed in FIFO manner

Let me elaborate

I have 2 AJAX requests A and B. Both A and B have there own call back functions. The app first makes request A then immediately afterward makes request B. Now the App expects A to return first. Now my question is what if B returns first. Which Call back will be executed?

I did some research and could not find any info on this issue. So I assumed that the browser would coordinate the callbacks. To make sure I wrote a little test. My test showed that regardless of which response returns first the first requests call back is always used first.

My question is what is the behavior? Also what techniques or methods are used to avoid such a case.

Majid
14.3k16 gold badges81 silver badges117 bronze badges
asked Sep 28, 2011 at 14:35

2 Answers 2

4

Look at the jQuery promise/deferred objects, they allow you to control this exact behavior.

$.when( $.ajax("test.aspx") ).then( $.ajax("test2.aspx") );

http://api.jquery.com/category/deferred-object/

answered Sep 28, 2011 at 14:37
Sign up to request clarification or add additional context in comments.

Comments

2

As you described the flow - if the request B returns first, then its callback will be called first.

You can always call the second ajax request when the first one suceed, for example:

function callbackA() { return true; }
function callbackB() { return true; }
$.ajax({url: '/my/url', data: {mydata: mydata}, success: function(data) {
 callbackA(data);
 $.ajax({url: '/my/url2', data: {mydata2: mydata2}, success: function(data) {}
 callbackB(data);
 });
});
answered Sep 28, 2011 at 14:56

1 Comment

On second thought, this is probably the most straightforward solution.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.