MJS MJS - 7 months ago 43
Javascript Question

jQuery - pass array of functions to ajax success callback

I'm fairly new with jQuery, and I'm trying to call two functions on successful ajax (since the documentation says as of 1.5 success callback can take an array of functions).

If I do this, everything works fine:

$.ajax({
url : sJSONFilePath,
dataType : 'json',
success : foo(data)
});


What do I need to do to pass in an array of functions? If I try the following, I get a "Uncaught TypeError: Cannot read property 'length' of undefined" error in the console:

$.ajax({
url : sJSONFilePath,
dataType : 'json',
success : [foo(data), bar(data)]
});


I was unable to find any examples of this feature being used. Thanks in advance, and sorry if this is dumb.

Answer

There's no need for an array, you can use the deferred syntax that was also introduced in jQuery 1.5:

$.ajax(...).done(foo).done(bar);

This is generally cleaner and much more extensible than passing callback functions as parameters to $.ajax and relatives.

From the $.ajax() documentation:

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). For convenience and consistency with the callback names used by $.ajax(), jqXHR also provides .error(), .success(), and .complete() methods. These methods take a function argument that is called when the $.ajax() request terminates, and the function receives the same arguments as the correspondingly-named $.ajax() callback. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.)

[but see the paragraph after, where it explains how .success, .error and .complete are now deprecated and replaced with .done, .fail and .always]