Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to run code after all ajax call completed under the for loop statement?

Tags:

jquery

ajax

each

I have a for loop statement, each loop will execute an ajax call.

$.each(arr, function(i, v) {
    var url = '/xml.php?id=' + v;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'xml',
        success: function(xml) {
            if ($(xml).find('Lists').attr('total') == 1) {
                // some code here
            }
        },
        complete: function() {
            // some code here
        }
    })
})

I want to run code after all ajax call completed under the loop, I have tried to place the code below to last line, it is not executed when the ajax call completed

    if (i == arr.length - 1) {
        // some code here
    }

Therefore, if I have 10 times of loop, there are 10 times of ajax call. I want to run a code after there 10 times of ajax call completed, any ideas?

Is it better to use .ajaxComplete() or .done() to achieve it?

Thanks

like image 364
Charles Yeung Avatar asked Nov 30 '25 19:11

Charles Yeung


1 Answers

Try using $.when()

var arr = [];
$.each(arr, function(i, v) {
    var url = '/xml.php?id=' + v;
    var xhr = $.ajax({
        url: url,
        type: 'GET',
        dataType: 'xml',
        success: function(xml) {
            if ($(xml).find('Lists').attr('total') == 1) {
                // some code here
            }
        },
        complete: function() {
            // some code here
        }
    });
    arr.push(xhr);
})

$.when.apply($, arr).then(function(){
    console.log('do')
})
like image 199
Arun P Johny Avatar answered Dec 03 '25 13:12

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!