Ajinkya
Ajinkya

Reputation: 22710

Synchronize Ajax call

I have a for loop inside which I am making a Ajax call which gives some response

for (var i in my_array)   
{  
   ajax_call()   
}  

I am firing multiple Ajax request sometimes the Ajax response is not in order of Ajax request. I want to get the response in order same as request.
Is there any way to achieve this without adding any delay to application ?

Upvotes: 0

Views: 245

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Instead of a loop you could use a recursive function:

function sendAjax(myArray, index) {
    $.ajax({
        url: '/someurl',
        type: 'POST',
        data: { id: myArray[index].id },
        success: function(result) {
            // TODO: do something with the result of the AJAX call

            if (index < myArray.length) {
                // proceed with the next call if we still have
                // elements in the array to process
                sendAjax(myArray, index++);
            }
        }
    });
}

and then trigger:

sendAjax(my_array, 0);

This way it's guaranteed that responses will arrive in the same order as requests simply because no other request is made before the first completes.

This being said, sending multiple AJAX requests like this is not a good idea. You should limit network connections as much as possible. It's better to send one big AJAX request containing all the array data instead of multiple smaller AJAX requests for each element of your array.

Upvotes: 2

Rene Pot
Rene Pot

Reputation: 24815

if you use jQuery ajax you could use async. This way JavaScript 'halts' until the AJAX call is done.

$.ajax({
  url: "test.html",
  context: document.body,
  async: false,
  success: function(){
    // do something here
  }
});

doc: http://api.jquery.com/jQuery.ajax/

Upvotes: 0

Related Questions