What Is AJAX
Modern AJAX-based
solutions for the Windows platform are based on
the XMLHttpRequest object. Google Maps
and Gmail are the two most
popular Web applications designed according to AJAX patterns
and
techniques. For AJAX, these were certainly the killer applications that
established its usefulness
and showed its potential.
Two combined elements make an AJAX application live and thrive. On one hand, you need to
serve users fresh data retrieved on the server. On the other hand, you need to integrate new
data in the existing page without a full page refresh.
The XMLHttpRequest Object
When the XMLHttpRequest object was first released, the Component Object Model (COM)
was ruling the world at Microsoft. The extensibility model of products and applications was
based on COM and implemented through COM components. In the late 1990s, the right and
natural choice was to implement this new component as a reusable automation COM object,
named Microsoft.XmlHttp.
As a result, in Mozilla browsers XMLHttpRequest looks like a native JavaScript object and can
be instantiated through the classic new operator:
// The object name requires XML in capital letters
var proxy = new XMLHttpRequest();
When the browser is Internet Explorer, the XMLHttpRequest object is instantiated using the
ActiveXObject wrapper, as shown here:
var proxy = new ActiveXObject("Microsoft.XmlHttp");
Internet Explorer 7.0
var proxy = new XMLHttpRequest();
An HTTP Object Model
Using
the XMLHttpRequest COM object from within .NET applications is nonsensical, as you can find
similar functionality in the folds of the System.Net namespace in the .NET Framework.
Important:
If you're going to use Microsoft ASP.NET AJAX Extensions or any other AJAXlike
framework for building your applications, you'll hardly hear about the XMLHttpRequest
object, much less use it directly in your own code. ASP.NET AJAX Extensions completely
encapsulates this object and shields page authors and application designers from it. You
don't need to know about XMLHttpRequest to write great AJAX applications, no matter how
complex and sophisticated they are. However, knowing the fundamentals of XMLHttpRequest
can lead you to a better and more thorough understanding of the platform and to more
effective diagnoses of problems.
The XMLHttpRequest object is designed to perform one key operation: sending an HTTP
request. The request can be sent either synchronously or asynchronously. The following listing
shows the programming interface of the object
interface XMLHttpRequest {
function onreadystatechange;
readonly unsigned short readyState;
void open(string method, string url);
void open(string method, string url, bool async);
void open(string method, string url, bool async, string user);
void open(string method, string url, bool async,
string user, string pswd);
void setRequestHeader(string header, string value);
void send(string data);
void send(Document data);
void abort();
string getAllResponseHeaders();
string getResponseHeader(string header);
string responseText;
Document responseXML;
unsigned short status;
string statusText;
};
Using the component is a two-step operation. First, you open a channel to the URL and specify
the method (GET, POST, or other) to use and whether you want the request to execute
asynchronously. Next, you set any required header and send the request. If the request is a
POST, you pass to the send method the body of the request.
The send method returns immediately in the case of an asynchronous operation. You write an
onreadystatechange function to check the status of the current operation and, using that function,
figure out when it is done.
Sending a Request
var xmlRequest, e;
try {
xmlRequest = new XMLHttpRequest();
}
catch(e) {
try {
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
}
}
The open method prepares the channel for the request; no physical socket is created yet,
though. To execute a POST statement, you need to add the proper content-type header.
The
Boolean argument indicates whether the operation is asynchronous:
xmlRequest.open("POST", url, false);
xmlRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlRequest.send(postData);
The send method opens the socket and sends the packet. In the preceding code snippet, the
method returns only when the response has been fully received.
An asynchronous request requires slightly different code:
xmlRequest.open("POST", url, true);
xmlRequest.onreadystatechange = CallbackComplete;
xmlRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlRequest.send(postData);
The CallbackComplete element is a placeholder for a JavaScript function that retrieves and processes
the response generated by the request.
Receiving a Response
The response of the request is available in two formats: as raw text and as an XML document.
The responseText property is empty if the state is 0 through 2—that is, no data has been
received yet. When the state transitions to 3 (receiving data), the property contains the data
received so far, interpreted using the character encoding specified in the response. If no character
encoding was specified, it employs UTF-8.
The responseXml property is not available until the full response has been downloaded and
successfully parsed to an XML document. If the body of the response is not XML or if the
parsing fails for any reason, the property returns null. It is important to note that the construction
of the XML document takes place on the client once the raw HTTP response has been
fully received.