202

I have coded like this:

$.ajax({ cache: false,
    url: "/Admin/Contents/GetData",
    data: { accountID: AccountID },
    success: function (data) {
        $('#CityID').html(data);
    },
    error: function (ajaxContext) {
        alert(ajaxContext.responseText)
    }
});

But when I look at the jQuery .ajax() documentation at the end it seems to suggest I should be coding like this below or at least it suggests adding a .done() and a .fail():

var request = $.ajax({ cache: false,
    url: "/Admin/Contents/GetData",
    data: { accountID: AccountID }
});

request.done(function (data) {
    xxx;
});
request.fail(function (jqXHR, textStatus) {
    xxx;
});

Update

If I code like this is it the same or is there some advantage to breaking it into three ?

$.ajax({ cache: false,
    url: "/Admin/Contents/GetData",
    data: { accountID: AccountID }
}).done(function (data) {
    xxx;
}).fail(function (jqXHR, textStatus) {
    xxx;
});
Alan2
  • 23,493
  • 79
  • 256
  • 450

4 Answers4

191

As stated by user2246674, using success and error as parameter of the ajax function is valid.

To be consistent with precedent answer, reading the doc :

Deprecation Notice:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

If you are using the callback-manipulation function (using method-chaining for example), use .done(), .fail() and .always() instead of success(), error() and complete().

Community
  • 1
  • 1
Michael Laffargue
  • 10,116
  • 6
  • 42
  • 76
  • This is what I thought but when I posted a few questions about status code earlier nobody was mentioning this even after I did. – Alan2 Jun 07 '12 at 12:38
  • @Gemma Trust the Dev team, if they say that it may be removed in future versions and that it's better to use the new ones, use the new ones. – Michael Laffargue Jun 07 '12 at 12:48
  • thanks and yes I will use the new way. Did you see my update at the end. I am wondering if my last code snippet is the best way to do it. I am not sure what the advantage of breaking up the code into three is. – Alan2 Jun 07 '12 at 13:06
  • @Gemma it'll do the same thing, it's a coding technique called http://en.wikipedia.org/wiki/Method_chaining, there's pros and cons about using it. You may look at this for information : http://stackoverflow.com/questions/1103985/method-chaining-why-is-it-a-good-practice-or-not – Michael Laffargue Jun 07 '12 at 13:11
  • 60
    I disagree. The references talks about the *callback-manipulation functions* (e.g. `.error`, `.success`) which *are* deprecated in favor of the more universal Deferred pattern, but the *parameters to the `ajax` method are not deprecated* and are both valid and acceptable - even in jQuery 1.9/2.0! In all current forms, `ajax` still returns a Deferred; possibly with already-attached Deferred callbacks. – user2246674 Apr 18 '13 at 05:45
  • @user2246674 you're right, it's been a while I must have misread the question. I corrected the answer, feel free to enhance it if you think it should. – Michael Laffargue Apr 19 '13 at 07:24
  • 2
    Here it is, jQuery 1.9, and success:, error:, and complete: are still usable. However, my question is, is .done() == to success: ? – TARKUS Jun 23 '13 at 19:29
  • 4
    @GregoryLewis From JQuery 1.10 source code : `jqXHR.success = jqXHR.done;`. – Michael Laffargue Jun 24 '13 at 06:21
  • 11
    I'd honestly prefer `success`, `fail`, `always`. – ahnbizcad Jul 01 '14 at 09:40
  • 5
    WOW, I misread the documentation as well. I literally thought the 'success'/'error' options for $.ajax were rewritten to 'done/fail'. It was just the callback method chains. Honestly, I think they should have switched the option names as well. That had me stumped for hours. – OzzyTheGiant Aug 22 '16 at 16:27
  • I want to know the same for jQuery 3.x version. Should I use done() & fail() or then() and catch() ? – Dipesh Raichana Jul 12 '18 at 06:33
  • Can anyone please share official documentation for this? I tried google and their official site and failed. – Lolitha Ratnayake Mar 15 '19 at 05:46
15

I want to add something on @Michael Laffargue's post:

jqXHR.done() is faster!

jqXHR.success() have some load time in callback and sometimes can overkill script. I find that on hard way before.

UPDATE:

Using jqXHR.done(), jqXHR.fail() and jqXHR.always() you can better manipulate with ajax request. Generaly you can define ajax in some variable or object and use that variable or object in any part of your code and get data faster. Good example:

/* Initialize some your AJAX function */
function call_ajax(attr){
    var settings=$.extend({
        call            : 'users',
        option          : 'list'
    }, attr );

    return $.ajax({
        type: "POST",
        url: "//exapmple.com//ajax.php",
        data: settings,
        cache : false
    });
}

/* .... Somewhere in your code ..... */

call_ajax({
    /* ... */
    id : 10,
    option : 'edit_user'
    change : {
          name : 'John Doe'
    }
    /* ... */
}).done(function(data){

    /* DO SOMETHING AWESOME */

});
Ivijan Stefan Stipić
  • 6,249
  • 6
  • 45
  • 78
14

In simple words

$.ajax("info.txt").done(function(data) {
  alert(data);
}).fail(function(data){
  alert("Try again champ!");
});

if its get the info.text then it will alert and whatever function you add or if any how unable to retrieve info.text from the server then alert or error function.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Yasir
  • 489
  • 5
  • 11
2

We will use .done, .fail instead of success, error when we migrate to jQuery from 1.x to 2.x or 3.x in our old existing application because jQuery is going to deprecate these methods. For example, when we make a call to server web methods and the server then returns promise objects to the calling methods (Ajax methods) these promise objects contain .done, .fail, etc. methods. Hence, we will do the same for the success and failure response. Below is an example (it is for a POST request the same way we can construct for a request type like GET...):

 $.ajax({
            type: "POST",
            url: url,
            data: '{"name" :"sheo"}',
            contentType: "application/json; charset=utf-8",
            async: false,
            cache: false
            }).done(function (Response) {
                  //do something when get response            })
           .fail(function (Response) {
                    //do something when any error occurs.
                });
RoastBeast
  • 1,059
  • 2
  • 22
  • 38
Sheo Dayal Singh
  • 1,591
  • 19
  • 11