SaeX SaeX - 1 year ago 74
Ajax Question

Only execute next AJAX call if previous one is done

I'm generating PDFs in the background through an AJAX call. Generating the PDF takes some time (about a second or so).

The below works fine, but the problem is that I run out of memory.
Hence I'd like to only start the computation (i.e. only issue the AJAX call) when the previous AJAX call is done.

I've played around with

async: false
but that freezes my page, which is unwanted behavior (and the use of
is deprecated anyhow).

My code:


var myid= $(this).data('myid');
var my_div = $(this);

url: "/my_ajax/" + myid + "/",
}).done(function (data) {
my_div.html(data.message + ' <a href="' + data.url + '">Download</a>');



<td><div id="div_260" data-myid="260">Queued..</div></td>
<td><div id="div_259" data-myid="259">Queued..</div></td>

Note the table is dynamically generated and generally contains 100+ rows.

Any idea on how to best approach this?

Answer Source

First of all create an array and push the DOM object in an array for all divs. Then create a function for ajax call and recursively call it for all the div. In this way you can achieve the next ajax call will be only performed after completion of the previous one.

 <script type="text/javascript">    

    var elementArray = [];

        $("div[data-myid]").each(function () {

    function doAjax(arrCount) 
        var myid = elementArray[arrCount].data("myid");
        var my_div = elementArray[arrCount];

            url: "/my_ajax/" + myid + "/",
            success: function (data) {              
                if (arrCount < elementArray.length-1) {
                    my_div.html(data.message + ' <a href="' + data.url +  '">Download</a>');

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