How To Handle AJAX Responses
By Kris Hadlock
Request and Response
There are many dimensions to the AJAX engine, each with its own importance. Once the engine does the work of sending the request and receiving the response, there are infinite ways to handle the response. The response is a crucial part of the process, as the user ultimately interacts with that response. This article explains in detail how to handle the AJAX response and provide feedback and on-demand updates to your users. We’ll start with the ready state of the request and move on to the response status, callback, and parsing of the response. Other parts of the response we’ll cover in this article include loading messages, error handling, and rendering the response data.
I’ve created a sample that can be viewed here and is available for download here. This sample includes an object-oriented AJAX engine, which can be reused in any AJAX application. Before discussing the response, I want to point out how to create the AJAX engine and make a request. First, let’s look at the code for the AJAX engine without the response handling, which we’ll add in just a bit:
To create this object and make a request, you only need the following two lines of code:
var ajax = new Ajax(); ajax.makeRequest(’GET’, ’xml/content.xml’, onResponse);
The second line of this code will reflect the request method of your choice, the path to the XML or server-side script that you’re requesting, and the callback method that you want to call when the response is received. Now that you have an understanding of the AJAX engine and how to make a request, let’s learn how to handle the response.