Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect completion of multiple async javascript $.ajax calls

I have a javascript function that enters a loop and issues an asynchronous ajax call for each loop. I need to know when ALL the ajax calls have returned and been processed, because I want to update the UI at that point.

The loop is as follows:

function sync_SyncLocalStorageToServer() {
    if (helper_IsAppOnline()) {
        $.log('sync_SyncLocalStorageToServer detects app is ONLINE');
        // Post each cached entry to the server - this is the main sync function
        for (var i = 0, len = localStorage.length; i < len; i++) {
            var lskey = localStorage.key(i);
            if (lskey.substr(0, 8) === 'response') {
                $.log('Sync found response with key=' + lskey);
                var postdata = localStorage.getItem(lskey); // Get the form data
                $.log('Calling server with ls response:' + postdata);
                var localkey = lskey;
                $.ajax({
                    type: "POST",
                    dataType: 'json',
                    url: "/Profile/PostForm",
                    data: { jsonpost: postdata },
                    success: function (data) {
                        if (data.rc == "success") {
                            localStorage.removeItem(data.localStorageKey); // Remove the relevant localStorage entry
                            $.log('ServerSuccess:' + data.message + ',removed localStorageKey=' + data.localStorageKey);
                        } else {
                            $.log('ServerUnhappy:' + data.message + ',did not remove localStorageKey=' + data.localStorageKey);
                        }
                    }
            , error: function (data) {
                $.log('ERR:' + data);
            }
                });
            }
        }
    }
    else {
        $.log('sync_SyncLocalStorageToServer detects app is OFFLINE');
    }
}

What is the easiest way for me to call my UI refresh function when the very last async ajax call has eventually returned from the server?

Thanks.

like image 321
Journeyman Avatar asked Jan 20 '23 12:01

Journeyman


2 Answers

Count how many times you execute an AJAX request, and then, count the number of times you have seen a call to the completed callback. Once the callback completed count equals the number of times you issued ajax calls, you know you are done.

var total = arr.length;
var count = 0;
for(var i = 0; i < arr.length; i++){
     $.ajax({
        // other options
        complete: function(){
            count++;
            if(count == total){ 
                // all finished!
            }
        }
     });
}

Note that I use the 'complete' callback, not 'success', since if one of the requests fail 'success' will not be called, but 'complete' will. Also, I declared the expected amount in 'total' first, instead of counting up in this example. This just avoid the unlikely (though technically possible) scenario of having all of the pending ajax requests finish before you've posted all of them, and therefore having a matching count.

like image 108
Matt Avatar answered Jan 31 '23 00:01

Matt


The easiest would be to attach a handler to the jQuery.ajaxStop event. If you require more hooks than this, you can attach to some of the other global AJAX events as well.

like image 42
Jon Avatar answered Jan 30 '23 22:01

Jon