- AJAX and Web 2.0
- Why Use AJAX?
- AJAX: An Example
- Using the AJAX Library
- Summary
AJAX: An Example
Now that you understand the advantages and disadvantages of AJAX, it is helpful to learn about the code behind AJAX requests. This section introduces an example of using AJAX and JavaScript Object Notation (JSON).
The XMLHttpRequest Object
The main object behind AJAX is the XMLHttpRequest object. This object exposes functionality that allows you to send and receive data (usually XML-based, but not required) from client-side JavaScript code to a server page.
XMLHttpRequest has six methods, listed in Table 1.1, and seven properties, listed in Table 1.2.
Table 1.1. XMLHttpRequest Methods
Method |
Parameters |
Description |
Abort |
Aborts the request that has been made. |
|
getAllResponseHeaders |
Returns a string of all response headers. |
|
getResponseHeader |
headerName |
Returns the value of a given response header. |
Open |
method, url method, url, async method, url, async, username method, url, async, username, password |
Opens the request to a specified URL. method defines the HTTP method that will be used (typically GET or POST). url defines the location of the page that is being requested. async is a Boolean that defines whether the request will be made asynchronously or not. |
Send |
content DOMString Document |
Sends the request to the server. DOMString is the XML that is to be sent as a string. Document is an XML DOM document |
setRequestHeader |
label, value |
Allows you to add a label and value to the HTTP header that is being sent to the server. |
Table 1.2. XMLHttpRequest Properties
Property |
Description |
onreadyStatechange |
Event handler that is fired when the readyState property changes. This will be a JavaScript function that handles the data that is returned to the client. |
readyState |
Returns the state of the XMLHttpRequest object. Possible values are 0 = not initialized 1 = open 2 = HTTP Headers received 3 = receiving 4 = loaded |
responseText |
Returns the complete response as a string. |
responseXML |
Returns the complete response (if it is XML) as an XML document object. |
responseBody |
Returns a binary encoded string of the response. |
Status |
Returns the HTTP status code of the request. HTTP status codes are defined at http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html. |
statusText |
Returns the HTTP status description of the request. |
Deep knowledge of the capabilities of the XMLHttpRequest object’s properties and methods is required learning for any AJAX developer. At its core, every library that encapsulates AJAX functionality (ASP.NET AJAX, AJAX.NET, Yahoo YUI, and so on) uses the XMLHttpRequest object.
The next section defines a simple AJAX JavaScript library that can be used to make AJAX calls in your web applications.
A Simple AJAX Library
As a developer, you probably have several (possibly hundreds of) scripts stuffed away somewhere that you reuse to accomplish specific tasks. One such script you can use for making AJAX calls is provided in Listings 1.1 through 1.3.
Listing 1.1. createAjaxRequest Function
//Section 1 var http_request = false; function createAjaxRequest(url, parameters) { http_request = createHttpRequestObject(); if (!http_request) { alert('Error creating XMLHTTP object'); return false; } http_request.onreadystatechange = getResponse; http_request.open('GET', url + parameters, true); http_request.send(null); }
This section contains the createAjaxRequest function. This method is called when you want to invoke an AJAX request. When this method is invoked, it first makes a call to createHttpRequestObject (described in Listing 1.2) to create an instance of the XMLHttpRequest object. After the object is returned, you need to do some error checking around this object to ensure that it was created correctly. Next (and most importantly), the object is configured by setting the onreadystatechange property to the getResponse function handler (described in Listing 1.3), and the request is opened (as asynchronous) and finally sent to the server.
Listing 1.2. createHttpRequestObject Function
//Section 2 function createHttpRequestObject(){ var request; if (window.XMLHttpRequest) { // IE7, Mozilla, Safari, etc. request = new XMLHttpRequest(); if (request.overrideMimeType) { request.overrideMimeType('text/xml'); } } else if (window.ActiveXObject) { // IE 6 and previous try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } return request; }
This section contains a helper function called createHttpRequestObject. Unfortunately, depending on the type of browser that you are using, there are many ways that you can (or should) create an instance of XMLHttpRequest. This method creates and returns the object instance of XMLHttpRequest that your browser supports.
Listing 1.3. getResponse Function
//Section 3 function getResponse() { if (http_request.readyState == 4) { if (http_request.status == 200) { var xmldoc = http_request.responseXML; alert(xmldoc.xml); } else { alert('There was a problem with the request.'); } } }
Although createAjaxRequest and createHttpRequestObject are somewhat boilerplate functions, the processing of the response occurs in the getResponse function, defined in Listing 1.3, getResponse.
The handler to execute this function was set up in the Section 1 createAjaxRequest method by setting the onreadystatechange property of the XMLHttpRequest object. This function gets fired every time the readyState property changes. It important to note that you will not be able to access the response until the readyState property is equal to 4, or loaded, so you first must check the status of the readyState before processing the response.
After your response has been loaded, you must perform another check on the HTTP status. If anything is wrong with your request (for example, 401-unauthorized, 404-page not found, and so on), then you can respond to that error here. In the example in Listing 1.3, the status is checked for a value of 200 (or OK), and then the function will process the request.
As soon as you make these two checks on the readyState and status properties of the XMLHttpRequest object, you can then process the response. In this example, the response is loaded into an XML Document object, and then the XML is displayed in a message box to help confirm the results.
Listing 1.4 is a complete code listing for all of the code described in this section.
Listing 1.4. Simple AJAX Library–Complete Listing
var http_request = false; function createAjaxRequest(url, parameters, callbackFunction) { http_request = createHttpRequestObject(); if (!http_request) { alert('Error creating XMLHTTP object'); return false; } http_request.onreadystatechange = getResponse; http_request.open('GET', url + parameters, true); http_request.send(null); } function createHttpRequestObject(){ var request; if (window.XMLHttpRequest) { // IE7, Mozilla, Safari, etc. request = new XMLHttpRequest(); if (request.overrideMimeType) { request.overrideMimeType('text/xml'); } } else if (window.ActiveXObject) { // IE 6 and previous try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } return request; } function getResponse() { if (http_request.readyState == 4) { if (http_request.status == 200) { var xmldoc = http_request.responseXML; alert(xmldoc.xml); } else { alert('There was a problem with the request.'); } } }