Eight Weeks of Prototype: Week 5, Ajax with Prototype
Handling the Ajax Response
Now that you know how to specify the callbacks for particular events that occur when performing an Ajax request, I will show you write to write the callback handler.
All of these callbacks are passed an instance of
Ajax.Response as the first argument. This object contains information about the request, such as the HTTP status code that resulted from the request, and any response data sent back. Full details about this class can be found at http://prototypejs.org/api/ajax/response.
My own preference is to call this parameter
transport. Whatever you call it, be consistent. Functions should be self-documenting, so you should be easily able to determine what the function is used for by its name and the naming of its arguments.
In writing a handler we are typically concerned with the response data. Typically we want to use this data somehow on the current page, whether it's text, HTML, JSON or XML. Because of this, when writing a response handler we are really only concerned with the
onSuccess handler, since
onFailure occurs only if something went wrong with the request.
Even if the Ajax request resulted in some error condition in your application, if the Ajax request succeeded you then need to handle your application error in the
The most commonly used values that are available in the transport variable are as follows:
status: The HTTP response code. An example of reading this value is shown in listing 8.
statusText: The text that corresponds to the response code, as sent by the server. Since different servers may send a slightly different string for certain response codes, you shouldn't rely on this value.
responseText: This is any data that is sent back from the request as a string.
responseXml: If data was sent from the server in XML format (with the correct content type header of
text/xml), this variable contains the response as a document object.
responseJSON: If the data was sent back from the server in JSON format, you can read the data from this array. In the next section I will show you how to do this. Note that the response from the server must use the
application/jsoncontent type header.
You can read any of these properties from the first argument that is sent to the request handlers. In the previous section I called this variable
Listing 9 shows identical functionality to the
Ajax.Updater example in Listing 3, however, in this example we read the
responseText variable and update the element accordingly. This example uses the same example HTML, shown in Listing 2.