jQuery ajax – headers are better than the success callback

If you’ve used jQuery for even a short period of time you will have probably come across the $.ajax method and several of it’s shortcut methods like $.getJSON or $.load

Within these methods there is usually a ‘success’ callback which fires when a 200 response is received from the server. 400 and 500 responses tend to trigger the ‘error’ callback.

So success and error are pretty generic all encompassing monsters who work for many tasks, but sometimes you need to be a little bit more clever about it.

Say you’ve written your own api which your pages are pinging. The api should be returning different response headers to let the requesting code know what’s happened. 401 for unauthorised, 404 for item not found, 200 when the response is good etc.

Wouldn’t it be good if you could then make your $.ajax call as clever as your api?

Well guess what, since jQuery 1.5 you can. $.ajax takes an property called ‘statusCode’ which is an object that can contain many different response codes. Helpfully it sends the same parameters as the success and error functions to the header depending on if it’s a success (200) or error (401 / 404) response.

You can see an example below where I request some JSON from an api, but it’s a really useful option when dealing with apis and more complete ajax calls.