Beauvais
Beauvais

Reputation: 2299

How to do multiple jQuery Ajax requests depending on eachother?

I am using jQuery 1.11 but what if I want to do several Ajax requests after eachother where they need to wait for eachother, is the only solution then to nest them like this:

// Ajax #1 -------------------------------
$.ajax({
  dataType: "json",
  url: "index.json",
  data: { urlVar1:val1,urlVar2:val2},
  success: function(data1) {

    // stuff for Ajax #1 ...

    // Ajax #2 ---------------------------
    $.ajax({
      dataType: "json",
      url: "index.json",
      data: { urlVarA:data1-val1,urlVarB:data1-val2},
      success: function(data2) {

        // stuff for Ajax #2 ...

        // Ajax #3 -----------------------
        $.ajax({
          dataType: "json",
          url: "index.json",
          data: { urlVarX:data2-val1,urlVarY:data2-val2},
          success: function(data3) {

            // stuff for Ajax #3 ...

          } // $.ajax.success #3
        }); // $.ajax #3 -----------------

      } // $.ajax.success #2
    }); // $.ajax #2 ---------------------


  } // $.ajax.success #1
}); // $.ajax #1 -------------------------

In real-life practice I need Ajax #1 to fetch a number of groups... Ajax #2 should process those groups and get subgroups and Ajax #3 should get individual lines from these subgroups.

In theory I could probably do these 3 Ajax calls with one call but this is just as much to get the understanding on how this can be done as I think the nested approach quickly gets too messy in my code.

Upvotes: 1

Views: 197

Answers (2)

Kevin B
Kevin B

Reputation: 95054

.then will make this much cleaner.

// Ajax #1 -------------------------------
$.ajax({
    dataType: "json",
    url: "index.json",
    data: { urlVar1:val1,urlVar2:val2}
}).then(function(data1){
    // Ajax #2 ---------------------------
    return $.ajax({
        dataType: "json",
        url: "index.json",
        data: { urlVarA:data1-val1,urlVarB:data1-val2}
    });
}).then(function(data2) {

    // stuff for Ajax #2 ...

    // Ajax #3 -----------------------
    return $.ajax({
        dataType: "json",
        url: "index.json",
        data: { urlVarX:data2-val1,urlVarY:data2-val2}
    });
}).then(function(data3) {
    console.log(data3);
}).fail(function(){
    console.log("something happened...",arguments);
    console.log(this.url)
});

Upvotes: 2

Mike Timmerman
Mike Timmerman

Reputation: 131

Maybe you can try this:

$.when( $.getJSON('index.json', { urlVar1 : val1, urlVar2 : val2 }), 
        $.getJSON('index.json', { urlVarA : data1-val1, urlVarB : data1-val2 }), 
        $.getJSON('index.json', { urlVarX : data2-val1, urlVarY : data2-val2 }) 
).then(function(data1, data2, data3){
    console.log(data1);
    console.log(data2);
    console.log(data3);
});

Upvotes: 0

Related Questions