I am creating a ajax utility for interfacing with my server methods. I would like to leverage jQuery 1.5+ deferred methods from the object returned from the jQuery.ajax() call. The situation is following.
The serverside method always returns a JSON object:
{ success: true|false, data: ... }
The client-side utility initiates the ajax call like this
var jqxhr = $.ajax({ ... });
And the problem area:
jqxhr.success(function(data, textStatus, xhr) { if(!data || !data.success) { ???? // abort processing, trigger error } }); return jqxhr; // return to caller so he can attach his own handlers
So the question is how to cancel invocation of all the callers appended success callbacks an trigger his error handler in the place mentioned with ????
?
The documentation says the deferred function invocation lists are FIFO, so my success handler is definitely the first one.
(UPDATE: Please note that currently jQuery Promises are not compatible with the Promises/A+ specification - more info in this answer.)
In your function where you create the AJAX request you can also create a deferred object and return a promise to the caller after binding its resolve and reject functions to the appropriate callbacks of the $.ajax request with some custom data verification, like this:
Now anyone will be able to use it like any promise like this to your function:
Or even just:
If you also add this:
then your caller will have (maybe more familiar) interface of .success() and .error() like with pure $.ajax() calls:
(The implementation of .complete() is left as an exercise for the reader.)
See this demos:
Here's another example pulled directly from a working project: