Depressio
Depressio

Reputation: 1379

Chaining a series of ajax calls

I have a series of ajax calls that need to run sequentially, but not synchronously. What's the best way to do this?

I know I can you $.when().then(), but that only works for two ajax calls, no? Ideally, I'd love to do something like:

var caller;
for (var i = 0; i < argObjects.length; i++) {
    if (typeof caller === 'undefined') {
        caller = $.when($.ajax(... data: argObjects[i]...));
    }
    else {
        caller.then($.ajax(... data: argObjects[i]...));
    }
}

In other words, just tack on a series on then's to chain 'em all together. But this isn't possible. Is there another way to do it with jQuery?

It's important to note that these calls CANNOT run at the same time. I could run a loop over them as set async: false, but that takes control away from the user while it processes which isn't good.

An alternative way of thinking about it would be to send everything in one call... but then how do I monitor the progress of that task as it runs? Say I have 10 weeks of data to update and I want to be notified as each week completes. If I sent 10 sequential ajax calls, each one could return and tell me that it has completed and I could update a progress bar of some sort. That's really the ultimate goal here.

I'll keep trying to wrap my head around deferreds in jQuery in the meantime.

Upvotes: 2

Views: 404

Answers (2)

jfriend00
jfriend00

Reputation: 707366

You can take a different approach using a success handler to launch the next ajax call and just use a counter to keep track of which request you're running:

var i = 0;
function run() {
    $.ajax(... data: argObjects[i]..., function() {
        i++;
        if (i < argObjects.length) {
            run();
        }
    });
}
run();

Upvotes: 2

amrinder007
amrinder007

Reputation: 1475

For sequential ajax calls what i have is calling another ajax inside the success of first ajax.

Like this:-

function ajax1(){
  $.ajax({
    url: "",
    data: dataString,
    type: "POST" ,
    dataType: "text",
    cache: false,   
    success: function(response_data){
        ajax2(); // call second ajax on success
    }
  });
}

function ajax2(){
  $.ajax({
    url: "",
    data: dataString,
    type: "POST" ,
    dataType: "text",
    cache: false,   
    success: function(response_data){

    }
  });
}

Upvotes: 1

Related Questions