SaeX SaeX - 4 months ago 13
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
async
is deprecated anyhow).

My code:

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

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

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

});


HTML:

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


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

Any idea on how to best approach this?

Answer

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 = [];

    $(document).ready(function(){
        $("div[data-myid]").each(function () {
            elementArray.push($(this));
        });
        doAjax(0);
    });

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

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

</script>
Comments