Reputation: 22710
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
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
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