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.
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);
}
});
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With