Reputation: 49371
I have a jQuery ajax call in a loop. However I do not want those ajax calls to be made simultaneously, I need the first ajax call to finish before going on to the next.
for (var i = 0; i < options.length; i++) {
jQuery.ajax({
url: "ajax_file.php",
data: //some data based on DOM tree
success: function(data){
//some DOM manipulation
}
});
}
I want the loop to continue executing only after the DOM manipulation in SUCCESS was executed (because the ajax call depends on the DOM tree). In theory I know I could set the ajax call to be async:false, but it is not recommended as it can freeze the browser.
Upvotes: 4
Views: 9141
Reputation: 6742
you can do something like this (pseudo-code):
var i =0;
doLoop();
function doLoop() {
//exit condition
if (i >= options.length) {
return;
}
//loop body- call ajax
$.ajax({
//...
success: function(data) {
//do your thing
i++;
//go to next iteration of the loop
doLoop();
}
});
}
Upvotes: 1
Reputation: 4588
Because async: false
is always a bad idea, I'd recommend something like this:
var recur_loop = function(i) {
var num = i || 0; // uses i if it's set, otherwise uses 0
if(num < options.length) {
jQuery.ajax({
url: "ajax_file.php",
data: //some data based on DOM tree
success: function(data){
recur_loop(num+1);
}
});
}
};
Upvotes: 8
Reputation: 141829
Setting async
to false will do that. Keep in mind that the web browser might lock up while the requests happen if you do them asynchronously.
jQuery.ajax({
async : false,
url: "ajax_file.php",
data: //some data based on DOM tree
success: function(data){
//some DOM manipulation
}
});
Upvotes: 1