66

how do i define the success and failure function of an ajax $.post?

zsharp
  • 13,656
  • 29
  • 86
  • 152

5 Answers5

117

The documentation is here: http://docs.jquery.com/Ajax/jQuery.ajax

But, to summarize, the ajax call takes a bunch of options. the ones you are looking for are error and success.

You would call it like this:

$.ajax({
  url: 'mypage.html',
  success: function(){
    alert('success');
  },
  error: function(){
    alert('failure');
  }
});

I have shown the success and error function taking no arguments, but they can receive arguments.

The error function can take three arguments: XMLHttpRequest, textStatus, and errorThrown.

The success function can take two arguments: data and textStatus. The page you requested will be in the data argument.

Jere.Jones
  • 9,915
  • 5
  • 35
  • 38
  • 28
    Please note the deprecation notice here: http://bit.ly/nuiyyE. As of jQuery 1.8 the success, error and complete methods will be deprecated instead use: done, fail and always. – hitautodestruct Jan 16 '12 at 14:06
  • 15
    If I read that correctly, the deprecation notice *only* applies to success() etc. on the returned jqXHR object, but not the ones specified using the settings object. So `$.ajax(url).success(...)` would be deprecated and should use `$.ajax(url).done(...)` instead. `$.ajax(url, {success: ...}` is still ok, I don't see deprecation notices on the individual descriptions of those settings members. – Alexander Klimetschek Oct 31 '12 at 19:36
  • 1
    One of these answers documents that which @hitautodestruct has mentioned. Please make the accepted answer if so inclined. – MrBoJangles Feb 05 '13 at 20:34
  • I interpret the docs & deprecation notice the same way as @AlexanderKlimetschek. However, even if it is not deprecated, the docs state that the error callback `handler is *not* called for cross-domain script and cross-domain JSONP requests`. That is motivation to switch to the pattern wherein the `fail` function is chained to the jqXHR object, rather than using the error option. – subsci Apr 03 '14 at 07:00
46

If you need a failure function, you can't use the $.get or $.post functions; you will need to call the $.ajax function directly. You pass an options object that can have "success" and "error" callbacks.

Instead of this:

$.post("/post/url.php", parameters, successFunction);

you would use this:

$.ajax({
    url: "/post/url.php",
    type: "POST",
    data: parameters,
    success: successFunction,
    error: errorFunction
});

There are lots of other options available too. The documentation lists all the options available.

Matthew Crumley
  • 101,441
  • 24
  • 103
  • 129
  • 5
    is there anything specific that is checked on the server side, during the url.php call? as in how would i know if the call was successful or erroneous? do i have to return true/false, null or something of the sorts? I'm trying this on struts, and a little confused what my action class should return. As in how would i know something went through successfully or didn't.. – KG - May 24 '10 at 13:32
  • 9
    @Kaushik: It's based on the HTTP status code returned by the server. Basically, anything except 2xx or 304 (not modified) is considered an error. The other conditions are if the connection times out or you can't connect to the server for some reason. – Matthew Crumley May 24 '10 at 14:24
33

using jQuery 1.8 and above, should use the following:

var request = $.ajax({
    type: 'POST',
    url: 'mmm.php',
    data: { abc: "abcdefghijklmnopqrstuvwxyz" } })
    .done(function(data) { alert("success"+data.slice(0, 100)); })
    .fail(function() { alert("error"); })
    .always(function() { alert("complete"); });

check out the docs as @hitautodestruct stated.

Li3ro
  • 1,837
  • 2
  • 27
  • 35
2

I was wondering, why they didnt provide in jquery itself, so i made a few changes in jquery file ,,, here are the changed code block:

original Code block:

    post: function( url, data, callback, type ) {
    // shift arguments if data argument was omited
    if ( jQuery.isFunction( data ) ) {
        type = type || callback;
        callback = data;
        data = {};
    }

    return jQuery.ajax({
        type: "POST",
        url: url,
        data: data,
        success: callback,
        dataType: type
    });  

Changed Code block:

        post: function (url, data, callback, failcallback, type) {
        if (type === undefined || type === null) {
            if (!jQuery.isFunction(failcallback)) { 
            type=failcallback
        }
        else if (!jQuery.isFunction(callback)) {
            type = callback
        }
        }
        if (jQuery.isFunction(data) && jQuery.isFunction(callback)) {
            failcallback = callback;

        }
        // shift arguments if data argument was omited
        if (jQuery.isFunction(data)) {
            type = type || callback;
            callback = data;
            data = {};

        }


        return jQuery.ajax({
            type: "POST",
            url: url,
            data: data,
            success: callback,
            error:failcallback,
            dataType: type
        });
    },

This should help the one trying to catch error on $.Post in jquery.

Updated: Or there is another way to do this is :

   $.post(url,{},function(res){
        //To do write if call is successful
   }).error(function(p1,p2,p3){
             //To do Write if call is failed
          });
yashpal
  • 326
  • 1
  • 3
  • 16
0

This style is also possible:

$.get("mypage.html")
    .done(function(result){
        alert("done. read "+result.length+" characters.");
    })
    .fail(function(jqXHR, textStatus, errorThrown){
        alert("fail. status: "+textStatus);
    })
Veenkar
  • 11
  • 1