108

Can anyone help me?
I am not able to understand the difference between success and .done() of $.ajax.

If possible please give examples.

whoan
  • 8,143
  • 4
  • 39
  • 48
Poonam Bhatt
  • 10,154
  • 16
  • 53
  • 72
  • where did you read about a done() method of $.ajax()? AFAIK the done method is related to $.Deferred object. Maybe are you talking about .complete() instead? – Fabrizio Calderan Jan 13 '12 at 08:37
  • 1
    on http://api.jquery.com/jQuery.ajax/ page – Poonam Bhatt Jan 13 '12 at 08:39
  • 2
    ok, it's jQuery 1.8 :) Since $.ajax return a promise from jQuery 1.5 this is a simple substitution for a matter of consistency (using the interface of deferred): done() take place of success(), fail() for error() and always() for complete() – Fabrizio Calderan Jan 13 '12 at 08:42
  • 2
    The real change is that you can attach multiple callbacks programmatically. Look at $.Deferred documentation page. – Fabrizio Calderan Jan 13 '12 at 08:48
  • Please see this for a better explanation : http://stackoverflow.com/a/14754681/781695 – user Mar 21 '14 at 08:14
  • @FabrizioCalderan in my case both `success` is fired before `done`, any idea what probably is going wrong ? http://stackoverflow.com/questions/26072445/jquery-ajax-success-fired-twice-its-that-how-it-behaves-in-latest-version – coding_idiot Sep 27 '14 at 07:42
  • 1
    Possible duplicate of [jQuery.ajax handling continue responses: "success:" vs ".done"?](http://stackoverflow.com/questions/8840257/jquery-ajax-handling-continue-responses-success-vs-done) – BuZZ-dEE Apr 07 '16 at 09:40
  • You should update the accepted anwser: @Keith is correct & has much more upvotes as a result. – Adriano Mar 20 '17 at 20:10

4 Answers4

116

success only fires if the AJAX call is successful, i.e. ultimately returns a HTTP 200 status. error fires if it fails and complete when the request finishes, regardless of success.

In jQuery 1.8 on the jqXHR object (returned by $.ajax) success was replaced with done, error with fail and complete with always.

However you should still be able to initialise the AJAX request with the old syntax. So these do similar things:

// set success action before making the request
$.ajax({
  url: '...',
  success: function(){
    alert('AJAX successful');
  }
});

// set success action just after starting the request
var jqxhr = $.ajax( "..." )
  .done(function() { alert("success"); });

This change is for compatibility with jQuery 1.5's deferred object. Deferred (and now Promise, which has full native browser support in Chrome and FX) allow you to chain asynchronous actions:

$.ajax("parent").
    done(function(p) { return $.ajax("child/" + p.id); }).
    done(someOtherDeferredFunction).
    done(function(c) { alert("success: " + c.name); });

This chain of functions is easier to maintain than a nested pyramid of callbacks you get with success.

However, please note that done is now deprecated in favour of the Promise syntax that uses then instead:

$.ajax("parent").
    then(function(p) { return $.ajax("child/" + p.id); }).
    then(someOtherDeferredFunction).
    then(function(c) { alert("success: " + c.name); }).
    catch(function(err) { alert("error: " + err.message); });

This is worth adopting because async and await extend promises improved syntax (and error handling):

try {
    var p = await $.ajax("parent");
    var x = await $.ajax("child/" + p.id);
    var c = await someOtherDeferredFunction(x);
    alert("success: " + c.name);
}
catch(err) { 
    alert("error: " + err.message); 
}
Keith
  • 150,284
  • 78
  • 298
  • 434
  • function creation before making the request, and set function after making request. Looks like both are same ... will you show me someother differences??? – suhailvs Jul 17 '13 at 11:24
  • 1
    @suhail - there aren't really any; in jQuery 1.6 there was `success`, in jQuery 1.8 that's been replaced by `done`. They work in the same way, but `done` is more consistent with the rest of jQuery. – Keith Jul 17 '13 at 13:02
  • @Keith so today, using .done is the same as using success? or there is something else even newer? – Roxy'Pro May 01 '18 at 20:23
  • @Roxy'Pro this was outdated when I answered it, I certainly wouldn't use this in 2018. `.done` was jQuery's early (and now dead-end) stab at what became `Promise` and that now has fairly comprehensive language support. In new projects I'd use `const response = await fetch(...)` instead. – Keith May 01 '18 at 20:32
6

In short, decoupling success callback function from the ajax function so later you can add your own handlers without modifying the original code (observer pattern).

Please find more detailed information from here: https://stackoverflow.com/a/14754681/1049184

Community
  • 1
  • 1
batbaatar
  • 5,448
  • 2
  • 20
  • 26
  • 1
    And below it the example maps out the equivalence of done => success, fail => error and always => complete – StuartLC Jan 13 '12 at 08:43
  • 25
    This answer misses the point. There is a difference between `success: ` used as a parameter and `.success()` as a method on a `jqXHR`. The latter is being deprecated, but the former is what the OP was asking about. – Alnitak Aug 23 '12 at 08:39
  • 2
    Success/error/complete are deprecated and based on AJAX state changes; done/fail/always are based on jQuery Deferred state changes. See http://api.jquery.com/category/deferred-object/. – mickeyreiss Dec 29 '12 at 02:22
  • 30
    i can't believe an answer that misinterprets the question is both the highest voted and the accepted solution... – Transcendence Nov 07 '13 at 02:16
6

.success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine.

The callbacks attached to done() will be fired when the deferred is resolved. The callbacks attached to fail() will be fired when the deferred is rejected.

promise.done(doneCallback).fail(failCallback)

.done() has only one callback and it is the success callback
Sameera Thilakasiri
  • 9,452
  • 10
  • 51
  • 86
  • 5
    It's worth noting that .success() does NOT get called when malformed JSON is sent back with a 200/OK status code. Specifically, I've run into an issue with webserver backend code generating NaN values and serializing them as javascript NaN (i.e. as a symbol, not string 'NaN') which is actually not valid JSON -- so the parsing of the response as JSON fails and .fail() is executed, but the response status is 200. But it's still true that success ONLY gets called with an OK status code; just wanted to point out that just because it's OK, doesn't mean it's 'success'ful ;) – Kasapo Dec 23 '15 at 22:05
1

success is the callback that is invoked when the request is successful and is part of the $.ajax call. done is actually part of the jqXHR object returned by $.ajax(), and replaces success in jQuery 1.8.

devdigital
  • 34,151
  • 9
  • 98
  • 120