1

It appears there are two ways to construct a success callback for jQuery, one form having 3 parameters and the other having only 1. Which of these is correct, and why do both forms appear?

Joel
  • 4,503
  • 1
  • 27
  • 41

3 Answers3

1

Look at the success function in the docs: http://api.jquery.com/jquery.ajax/

Function( Anything data, String textStatus, jqXHR jqXHR ) A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.

So the success function can take 3 parameters: the data returned, the status of the response, and the XHR object. Most of the time, you only need the first parameter.

Brennan
  • 5,632
  • 2
  • 17
  • 24
0

Maybe you are wondering why these two kind of ajax-using are both working?

$.post(url, callback-when-success);
$.post(url, data-to-be-posted, callback-when-success, server-return-datatype);

Let's have a look on the implementation(source code) of $.post()

jQuery.post = function( url, data, callback, type ) {
    /** the trick is right here ! **/
    // shift arguments if data argument was omitted
    if ( jQuery.isFunction( data ) ) {
        type = type || callback;
        callback = data;
        data = undefined;
    }

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

In fact, the $.post() always expects four parameter, and if you omit the data-to-be-posted(should be in the 2nd-pos)parameter, and the success-callback is placed on the 2nd-position, then the data would be assigned as undefined and the success-callback would still be the success-callback.

Lyfing
  • 1,778
  • 1
  • 19
  • 20
0

The then and done methods don't care how many parameters your callback has. A jQuery Promise1 can resolve with multiple arguments, and all these arguments will be passed to your callback. Which and how many of them you actually want/need to use is your business.

Some examples:

  • the animation queue .promise resolves with a single argument, the elements collection.
  • the $.ready.promise resolves with the jQuery function
  • the internally used Animation promises resolve with two arguments
  • the $.ajax promise resolves with the success, statusText, jqXHR arguments
  • a $.when(promise1, promise2, promise3, …) promise resolves with arbitrarily many arguments
  • a promise.then(function() { return … }) promise resolves with the single value

1: Notice that almost all other promise libraries put promises for single values only, see here for example.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375