0

What is a clean and readable way to chain jQuery ajax requests? I am trying to get out of this callback hell. I have ready many posts on this but they don't seem to answer this without even more complexity.

$.get('file1.php')
  .done(function(data) {
    $.get('file2.php')
      .done(function(data) {
        $.get('file3.php')
          .done(function(data) {

          })
          .fail(function() {
            showError();
          })
      })
      .fail(function() {
        showError();
      })
  })
  .fail(function() {
    showError();
  })
BarryBones41
  • 1,361
  • 1
  • 13
  • 30

2 Answers2

1

Note that the jqXHR object returned by the jQuery ajax requests can be chained with then:

$.get('file1.php').then(function () {
  return $.get('file2.php');
}, showError).then(function () {
  return $.get('file3.php');
}, showError).then(function ()
  ...
}, showError);
Hamms
  • 5,016
  • 21
  • 28
1

Try jQuery $.deffered object, you can not only make multiple ajax calls efficiently, but also make it chainable. Here you go:

var deferred = $.Deferred();

function getData() {

    var ajaxCall1 = $.get("file1.php", {}, null, 'jsonp');
    var ajaxCall2 = $.get("file2.php", {}, null, 'jsonp');
    var ajaxCall3 = $.get("file3.php", {}, null, 'jsonp');

    $.when(ajaxCall1, ajaxCall2, ajaxCall3)
     .done(function (response1, response2, response3) {
        // Your logic come here
    });

    return deferred.promise();
}

getData()
.then(
    function () {
        alert('Success');
    }, 
    function (response1, response2, response3) {
        alert('Response1 :' + response1
                     + 'Response2 :' + response2
                     + 'Response3 :' + response3);
    }
);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123