Keith E. Truesdell Keith E. Truesdell - 1 year ago 88
Ajax Question

jQuery load function after all other AJAX calls are complete

I have jquery .each loop going through an array. For each item in the array it is doing an AJAX call. When all the AJAX calls are complete, I want to reload part of the page using the .load() method. However this creates an endless loop if I use the .ajaxStop() method.
How can I achieve this?

Code below...

This is the part for when the button is clicked

$.each(remMems, function( index, value ) {
url: 'components/update_members.php',
type: 'POST',
data: {'memberbadge':value, 'function':'removemember'},
timeout: 6000
}); //end ajax call

//if its the last item, then refresh the area
if (index == lastitem) {
}); //end the for each loop

And this is the method/function called when the each loop is complete to refresh the section of the page

function refreshMembers() {
$('#listwrapper').load('members.php' + ' #ert_members');

Answer Source

You can use your loop to create an array of deferred objects. You can then apply that array to $.when and call the load() method. Try this:

var requests = [];
$.each(remMems, function(index, value) {
        url: 'components/update_members.php',
        type: 'POST',
        data: {
            'memberbadge': value, 
            'function': 'removemember'
        timeout: 6000

$.when.apply($, requests).done(function() {
    $('#listwrapper').load('members.php #ert_members');

Note that a better method entirely would be to modify your update_members.php to take an array of value and only make a single AJAX call.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download