Making your own success()

Earlier on during the development of Specify, we faced the need to extend some of jQuery’s ajax functionality.

Specify makes heavy use of jQuery’s various ajax functions in order to request various pieces of the UI as the user navigates the site. In fact, there are only 3 real “pages” in the traditional sense – almost everything happens without any page refreshes. This includes handling the submissions and responses for a few dozen form elements.

Normally, jQuery assumes that any response that doesn’t trigger an error (404, a timeout, a JSON parsing error) is “successful.” This certainly is useful, but wouldn’t it be even more useful if jQuery’s ajax functions could also judge whether or not a request was successful based on what is actually contained in the response?

We accomplished this by adding our own global success() and error() functions which wrap around the default jQuery.ajax() ones. These check for the existence of either HTML elements with certain class names (if it was an HTML request) or a root-level JSON node of certain names. This means that we can have the server send back something like {“ERROR”:”This is an arbitrary error!”} and the ajax() function will react as if a “real” error has occurred, which is exactly what we want.

Code after the jump…

Since jQuery.ajax() is called internally by .load(), .getJSON(), .get(), .post() and .getScript(), this modification also affects those functions. Note that SpecifyHandleMessage() and SpecifyHandleError() are defined elsewhere and handle the actual display of the error or message to the user.

Also note that the entire snippet is enclosed in a self-executing function. This creates a closure and ensures that the variables are politely scoped!