tags:

views:

65

answers:

3

I have an array of data (arrData) which I loop around (10 elements), calling an ajax request on each. As it stands at the moment each ajax call is made in parallel. This means the server receives 10 calls all at once and sends back the data in whatever order it calculates each in. To relieve the server slightly I want to now queue my calls. Therefore, when one set of data is received by ajax it calls the next lookup. Is there any way method of doing this built in to jquery or should I hack my loop and add a recursive callback to each?

$.each(arrData, function(k,v) {
    $.getJSON(lookupPath,
        { key:k, val:v },
        function(data) {
            console.log(data); //loopback here?
        }
    );
});

UPDATE: I went with the following (as suggested by Scott M.) to get this done:

function doLookup() {
    if(k < arrData.length) {
        var v = arrData[k];
        $.getJSON(lookupPath,
            { key:k, val:v },
            function(data) {
                console.log(data);
                k++;
                doLookup();
            }
        );
    }
}

var k = 0;
doLookup();
A: 

ajax in jQuery has an option to enable synchronous mode or not.

$.ajax({async: false});

http://api.jquery.com/jQuery.ajax/

Angelo R.
There is a massive difference between queuing AJAX requests, and making them synchronous. Synchronous requests will lock up the browser whilst the requests are in progress.
Matt
this makes the browser hang and wait for the call to come back before continuing
Scott M.
Ah, I wasn't aware of the lock-up issue. I've never hit this problem myself, so I've never needed to use it before. Thanks for pointing this out Matt, Scott M.
Angelo R.
I've just tried this method and you are right Angelo R. it does work. Unfortunately as Matt and Scott M. state it does cause the browser to hang and disable all further functionality until the last response is received.
The Artful Benny
+2  A: 

perhaps you could refactor your server-side code so that it can accept one request and provide one response with all the data you need. This would let you process your data sequentially and within only one thread.

EDIT:

In response to the comment below:

if you absolutely need the calls to be sequential, then you will need to recursively call the getJSON() method. This will guarantee your AJAX requests are separate and in order.

Scott M.
This seems a good solution to me. The only issue I have with it is I want to be able to see each result build up on the page so a user can be looking at the top result before the next has been brought back. Your way, whilst being kinder to the server, would bring back all data at once with a longer delay before anything is displayed.
The Artful Benny
A: 

I don't think there is any way to do this in jQuery out of the box. It looks like you're going to have to create a callback function on the Ajax call's success and run it for each element of your array.

Hooray Im Helping