John Slotsky
John Slotsky

Reputation: 171

AJAX - Wait until response before making next AJAX call

I made a function which loops through every div tag with with class="health_report", for each div it makes an AJAX call. The only issue is that it makes like 50 AJAX calls (assuming I have 50 DIV tags) immediately. This would be okay, but for my purposes I need it to wait until the first AJAX call is complete (the success function is triggered) moving onto the next DIV tag. Heres the code:

$('.health_report').each(function(i, obj) {
    //  FIRST AJAX CALL
    generateHealthReport();
});

    function generateHealthReport(fileID,filter,slug,reportID,importance,reputation) {

        $.ajax({
            type: "POST",
            url: ajaxurl,
            data: {
                "action": 'generateHealthReport'
            },
            dataType: "html",
            success: function (returnData) {
               //   do something

            }
        });
    }

So something I tried which should work was adding a timer to the loop

How can I make it so the loop (using a JQuery called timing http://creativecouple.github.io/jquery-timing/)

so the code became this:

$('.health_report').each($).wait(3000,function(i, obj) {
    //  FIRST AJAX CALL
    generateHealthReport();
});

The loop now pauses for 3 seconds between iteration which gives the first AJAX call time to complete before the loop moves to the next DIV tag. This makes the AJAX calls happen the way I need them to, but for some reason its glitchy, sometimes the HTML response that comes back is only part of the HTML that should be getting returned. Is there another way to do this? How can I make the loop pause until the AJAX call it makes has completed?

Upvotes: 0

Views: 1707

Answers (1)

lilezek
lilezek

Reputation: 7384

You can use ajaxComplete or option complete from ajax:

$.ajax({
    type: "POST",
    url: ajaxurl,
    data: {
        "action": 'generateHealthReport'
    },
    dataType: "html",
    success: function (returnData) {
       //   do something

    }
    complete: function() {
       // This is called after completion of Ajax.
       // nextAjax();
    }
});

Upvotes: 1

Related Questions