Multiplay Labs

tech hits and tips from Multiplay

Using the jQuery deferred object pipe method to validate success data

with one comment

Often I’ll make an AJAX call with jQuery to retrieve some data and while that data might be not be erroneous, it might not be exactly what I want. A typical solution to this is to validate the data in the success callback and call out to an external error handler if it fails. However, jQuery provides the capability of setting a failure callback and it would be nice to use that without needing to have to resort to some horrible code like:

var errorHandler = function() {
	url: '/my_ajax_call', 
.done(function(data) {
	if(data.success !== 'true') {
	} else {
		// do the good stuff

The problem with the above is that you lose all the benefits of jQuery’s deferred objects[1] and as such if you wanted to attach additional error handlers, you’d have to update the done callback to call them each time which just isn’t feasible when you might be passing around your AJAX promise object all over the place.

However, there is a better way which allows you to leverage the full power of the deferred/promise object system by using the pipe[2] method.

	url: '/my_ajax_call', 
.pipe(function(data, textStatus, jqXHR) { 
	if(data.success !== 'true') {
		var deferred = $.Deferred(); 
		deferred.rejectWith( this, [ jqXHR, textStatus, 'invalid' ] ); 
		return deferred; 
	return jqXHR; // return the original deferred object
.done(function() { 
	alert('Hurray, a success!');
.fail(function() { 
	alert('Boo, a failure!');

In the above code, pipe accepts as it’s first argument a function that filters the done callback parameters before the callbacks functions are actually called. Returning null from pipe allows the unfiltered values to pass through, but returning a deferred object will apply the callbacks against that new one, rather than the original. As a result, you can return a deferred object in a failure state to force the failure callbacks to trigger. As you’ll note, using the rejectWith method of the deferred object allows by to fully set what the callbacks evaluation context will be and what arguments it will get. For compatibility, I follow the exact same setup as the defaults, but you’ll see I have set a custom error string.

Because pipe is chainable, you can add multiple of these further down the line. Pipe also accepts additional parameters for filtering other callbacks too. This way it’s much easier and cleaner to validate data and handle errors with the additional flexibility of the deferred object system.


Written by Andrew Montgomery-Hurrell

March 9th, 2012 at 11:18 am

Posted in Hackery,Javascript

One Response to 'Using the jQuery deferred object pipe method to validate success data'

Subscribe to comments with RSS or TrackBack to 'Using the jQuery deferred object pipe method to validate success data'.

Leave a Reply

You must be logged in to post a comment.