Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Adobe Flash

How To Handle AJAX Responses

  • Print
  • + Share This
User interaction drives Web sites. It's essential to understand how to handle the responses, especially with new forms of interaction such as AJAX. Kris Hadlock covers the essentials of the AJAX request-and-response process that you need to know to be ready for user interaction.

Digg!
Like this article? We recommend

By Kris Hadlock

For more information on Web design, visit our Web Design Reference Guide or sign up for our Web Design Newsletter.

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:

document.write("<script type=\"text/javascript\" src=\"js/HTTP.js\"></script>");
function Ajax()
{
  this.toString = function() { return "Ajax"; }
  this.http = new HTTP();

  this.makeRequest = function(_method, _url, _callbackMethod)
  {
    this.request = (window.XMLHttpRequest)? new XMLHttpRequest(): new ActiveXObject("MSXML2.XMLHTTP");
    this.request.onreadystatechange = _callbackMethod;
    this.request.open(_method, _url, true);
    this.request.send(_url);
  }
}

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.

  • + Share This
  • 🔖 Save To Your Account