Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery continue loop execution after ajax success

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.

like image 406
Nathan H Avatar asked Dec 28 '22 14:12

Nathan H


1 Answers

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);
            }
        });
    }
};
like image 84
binarious Avatar answered Dec 31 '22 15:12

binarious