XMLHttpRequest Object in AJAX2006-10-28
| Table of Contents: |
| Rate This Article: | Add This Article To: |
XMLHttpRequest Object in AJAX - ' Initializing Requests ' ( Page 2 of 2 )
I recently wanted to join a popular online community. But when I filled out the registration form and clicked Submit, it responded, "User ID already taken." Why did I have to type in all my personal data and then find out that I had to make a change?
Surely, this has happened to you. And as a software developer, you have written applications that similarly require a unique value, such as userid, which require that the user send the entire thing before your code can deal with the data.
Fortunately, one attribute of AJAX can help you sidestep this problem. AJAX provides dynamic form validation by validating a field value before a form is submitted, so the user doesn't need to keep trying to find a login name that isn't already taken.
Asynchronous JavaScript and XML (AJAX) combines the XMLHttpRequest object with JavaScript and XML Document Object Model (DOM) technologies to provide asynchronous interaction between a Web client and a server. With AJAX, a form field value is sent to the server without posting the web page to the server; the server response is returned without reloading the Web page. You can also use AJAX techniques with JScript, Microsoft's implementation of ECMAScript scripting language specification.
The "asynchronous" in AJAX implies that the processing of a JavaScript/HTML page continues while a XMLHttpRequest is sent to the server and a response returned. With a asynchronous request, a HTTP request's send() method returns immediately, thus providing dynamic interaction between Web page and server.
How might you put this to use? You might use AJAX to create a Web form that's auto-completed as a user begins to add data to the form. For example, a form that requires employee information would have the name data fill in after his employee ID was entered.
Overview of XMLHttpRequest
The XMLHttpRequest object provides asynchronous communication between a client application, which may be an HTML/JScript page, and a server application, which may be an ASP page. The XML data received in a response may be rendered on the client side using XML DOM and XSLT.
Microsoft in IE 5 introduced XMLHttpRequest for Windows as an ActiveX component. Internet Explorer 6 also implements XMLHttpRequest as an ActiveX object. In IE 7, XMLHttpRequest was introduced as a window object property.
The XMLHttpRequest object provides various attributes/properties and methods to implement HTTP client functionality, and they are summarized in Table 1. In subsequent sections, I discuss procedures to use these attributes in an application.
Table 1. XMLHttpRequest Attributes/Properties
| Attribute/Property | Description |
|---|---|
| onreadystatechange | Specifes the callback method for asynchronous requests |
| readyState | Retrieves the current state of a HTTP request. |
| responseText | Retrieves the server response as text. |
| responseXML | Retrieves the server response as an XML DOM object. |
| responseBody | Retrieves the response body. |
| status | Retrieves the HTTP status code of the request. |
| statusText | Retrieves the text of the HTTP status. |
The XMLHttpRequest object methods are used to create an XMLHttpRequest object, open a request, set request headers, get and set response headers, and send a request. The methods available are shown in Table 2. Optional parameters are shown in brackets.
Table 2. XMLHttpRequest Methods
| Method | Description |
|---|---|
| abort() | Cancels the current HTTP request. |
| getAllResponseHeaders() |
Retrieves all the response headers if readyState value is 3 or 4. Returns null if readyState is 0, 1, or 2.
|
| getResponseHeader(string header) |
Returns a specified response header if readyState value is 3 or 4. Returns null if readyState is 0, 1, or 2.
|
| open(string method, string url[, boolean asynch][, string username][, string password]) | Opens a HTTP request with a specified method and URL |
| send(data) | Sends a HTTP request to the server and recieves an XML response. |
| SetRequestHeader(string headerName, string headerValue) |
Sets HTTP request headers if |
Initializing an HTTP Request
The procedure to send an asynchronous request with XMLHttpRequest is as follows:
- Initiate a request from an HTML page event.
- Create an
XMLHttpRequestobject. - Open the
XMLHttpRequestobject, which requires you to specify the URL to which the request is sent. - Register a callback method that is invoked when the request state changes.
- Send the HTTP request.
- Process the request on the server and send a response to the web browser.
- Update page content on the browser.
As mentioned, an HTTP request may be initiated from an HTML page event. In the following example, we invoke the JScript function getGrades() with the onkeyup event. In the getGrades() function, we create an XMLHttpRequest object and send a HTTP request to the server. The example form is used to refresh a Web page with grades for a specified user id.
<form id="form1" method="post">
<table>
<tr><td>User Id:</td><td><input type="text"
size="20"
id="userId"
onkeyup="getGrades()"></td>
<td></td>
</tr>
<tr><td>.NET Programming Grade:</td><td><div id="netDiv"></div></td>
</tr>
<tr><td>Java Programming Grade:</td><td><div id="javaDiv"></div></td>
</tr>
</table>
<form>
When the getGrades() function is invoked, a HTTP request is sent for each modification to the userId input field userId. When it finds a match, a server response is returned with which the form is updated.
Creating an XMLHttpRequest Object
Before a client application may send a HTTP request, you need to create an XMLHttpRequest object. IE 5 and 6 implement XMLHttpRequest as an ActiveX component, and IE 7 implements XMLHttpRequest as a window object property. In IE 6, create an XMLHttpRequest object with the following script, which may be specified in a JScript client application.
<script language="JScript">
if (window.ActiveXObject) {
var req = new ActiveXObject("Microsoft.XMLHTTP");
</script>
In Internet Explorer 7, XMLHttpRequest is implemented as a window object property. Create an XMLHttpRequest object in IE7 with the following script that may be specified in a JScript application.
<script language="JScript">
if (window.XMLHttpRequest) {
var req = new XMLHttpRequest();
}
</script>
After an XMLHttpRequest object has been created, the readyState property is set to 0. At this stage, an XMLHttpRequest object has been created, but not initialized.
Opening an HTTP Request
After you create an XMLHttpRequest object, open an HTTP request using the open(string method, string url[, boolean asynch][, string username][, string password]) method. The open() method initializes a HTTP request, but does not send the request. The HTTP method and server URL are required parameters of the open() method. The URL may be relative or absolute. Boolean parameter asynch specifies if the HTTP request is asynchronous or synchronous. The default value of the aynch is true.
In the following example, an HTTP request is opened with HTTP method GET and a relative URL to an ASP page, validate.asp. The userId parameter is included in the URL. JScript method encodeURIComponent(String) encodes the userId value.
<script language="JScript">
var userId=form1.userId.value;
req.open("GET", "validate.asp?userId="+ encodeURIComponent(userId), true);
</script>
After the open() method has been invoked, the readyState property is set to 1. Attributes responseText, responseXML, status, and statusText are set to their initial values.
Sending an HTTP Request
After opening a HTTP request, register a callback method using the onreadystatechange property. The callback method is invoked when the value of the readyState property changes. In the following example, we register the callback event handler requestCallback with the XMLHttpRequest object using the onreadystatechange property.
<script language="JScript"> req.onreadystatechange=requestCallback; </script>
Next, send an HTTP request with the send(data) method. The data parameter may be a string, an array of unsigned bytes, or an XML DOM object. The data may be set to null. The send() method is asynchronous if the boolean parameter asynch of the open() method is set to true, and synchronous if the asynch is set to false. A asynchronous method returns immediately; a synchronous method does not return until the HTTP request is complete and the entire response has been received.
<script language="JScript"> req.send(null); </script>
After the send() method has been invoked, the readyState property value is set to 2. At this stage, the status and headers are not available. When the HTTP request has completed, the readyState property is set to 4.
Processing an HTTP Request
On the server side, the HTTP request is received and processed by an ASP page and an XML response is returned. Retrieve the parameter values in the request with the Request object.
<%
userId=Request.QueryString("userId")
%>
Create an XML response by obtaining data from a database for a specified user id. Send an ASP page response using the Response object. Here's an example of an XML response containing class grades:
<% Response.Write "<grades><java>B grade</java><NET>A grade</NET></grades>" %>
Processing an HTTP Response
In the previous section, we registered a callback method with the XMLHttpRequest object. The callback method is invoked when the readyState property changes; a value of 3 indicates that data was received, but response headers and status are not completely available. At this stage, the responseXML property value is null. The responseText property value contains partial response data. A readyState property value of 4 indicates that response headers are completely set, and all the data has been received. In the requestCallback method, check the value of the readyState property. If its property value is 4 and the status is 200 (which corresponds to "Ok"), invoke the JScript function response(), which updates the page content, as shown in following script.
<script language="JScript">
function requestCallback(){
if(req.readyState==4){
if(req.status==200){
response();
}
}
}
</script>
In the response() function, retrieve the values of the responseXML, responseBody, and responseText properties to modify the page content on the page that initiated the HTTP request. Process the XML DOM object in the responseXML property to obtain element and attribute values.
<script language="JScript">
function response(){
var xmlResponse=req.responseXML;
var textResponse=req.responseText;
}
</script>
For example, obtain the grade in .NET using the getElementsByTagName method, as shown in the following script.
<script language="JScript">
function response(){
var netGrade=xmlResponse.getElementsByTagName("NET")[0].firstChild.nodeValue;
}
</script>
Set the value of the 'net' id div with the innerText or innerHTML properties.
<script language="JScript">
function response(){
var netDiv=form1.netDiv;
netDiv.innerHTML=netGrade;
}
</script>
Ta da! And the end of all this, your Web page is refreshed with data for a specified user id, without actually posting the Web page to the server.
![]() |
|


