4

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.

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

can I just create a var at the top of the function, and adjust that? Will there be any possible scoping or threading issues doing it this way? Thanks very much.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.