eik3
eik3

Reputation: 115

Return jQuery deferred from error block in Ajax call

I'm trying to load a file via jQuery Ajax. If the first locations fails, it should try to retrieve it at another path. This basically works, the request goes to the alternative URL, but I don't get the jQuery deferred back from loadFile() that I need further down.

How can I make loadFile() always return the right deferred?

loadFile = function(url) {
  return $.ajax({
    url: u,
    error: function() {
      return $.ajax({
        url: '/otherPath/' + u
      });
    }
  });
};

loadFile('stats.xml').then(parseXml).then(...)

Upvotes: 1

Views: 176

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123423

Despite the 2nd request inside error:, loadFile() is still returning the initial Deferred() which will have failed.

To be able to chain Deferreds capable of their own state, you'll want to use .then():

loadFile = function(url) {
  return $.ajax({
    url: u
  }).then(null, function() {
    return $.ajax({
      url: '/otherPath/' + u
    });
  });
};

Example: http://jsfiddle.net/9sHK7/

Upvotes: 1

Related Questions