How To - Bulletproof Ajax Requests

TBD Need an example of a really bulletproof Ajax.Request, since 99% of the examples people can find online "omit error handling for brevity".

This is a start in that it at least has onFailure and onException handlers, but it's only a start. It demonstrates the four basic error conditions:

  • The request was successful, but did not return the data in the expected format (in this example, we're expecting JSON as the response body).
  • Your page returned correctly and successfully, but said the operation failed (in this example, the record wasn't found). This isn't necessarily a failure, but it needs to be handled.
  • The request failed (404 and that kind of thing).
  • The on0 callback is called if the connection to the web server failed, typically because the the server is overloaded or has gone down since the page was loaded. While these conditions are rare, otherwise a failed connection calls the onSuccess handler!
  • An exception occurred in one of the callbacks.


function retrieveRecord(target, recid)
    target = $(target);
    if (!target) {
    new Ajax.Request("getrecord.php", {
        parameters: {
            id: recid
        onSuccess: function(response) {
            if (!response.responseJSON)
                // Request completed, but gave an invalid response:
                // We were expecting a JSON response body
                showError("Error loading record #" + recid);
            else if (!response.responseJSON.record)
                // Request completed and gave a valid response -- saying the record
                // wasn't found on the server
                showError("Record #" + recid + " not found");
                // Request completed and returned the record.
                displayRecord(target, response.responseJSON.record);
        on0: function (ajaxResponse) {
            // connection failed, typically because the server is overloaded or has gone down since the page loaded
            showError("Connection failed");
        onFailure: function(response) {
            // Request failed (404, that sort of thing)
            showError("Error loading record #" + recid);
        onException: function(request, ex) {
            // An exception was thrown in one of our callbacks
            showError("Exception loading record #" + recid);
function displayRecord(target, record)

Separate from an example that just handles errors robustly, we might want examples of the various onXYZ handlers. But 9 times out of 10, I don't know that the client code really cares which specific error occurred, just that it didn't work.

— T.J.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License