Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


A Detailed Explanation of the XMLHttpRequest Object : Page 4

The XMLHttpRequest object is at the technological root of all AJAX and Web 2.0 applications. Although software vendors and the open source community now supply many AJAX frameworks that simplify using the XMLHttpRequest object, it's still worth your time to know the fundamentals.




Full Text Search: The Key to Better Natural Language Queries for NoSQL in Node.js

Sending a Request
In AJAX, many requests that use the XMLHttpRequest are initiated from a HTML Event such as a button click (onclick) or a key press (onkeypress)that invokes a JavaScript function. AJAX has various applications including form validation. Sometimes a unique form field is required to be validated before the rest of the form may be filled. For example a registration form that requires a unique UserID. Without validation of the UserID field with AJAX the complete form would have to be filled and submitted. If the UserID is not valid, the form would have to be re-submitted. For example, a form field for a Catalog ID that must be validated on the server might be specified as follows.

<form name="validationForm" action="validateForm" method="post"> <table> <tr><td>Catalog Id:</td> <td> <input type="text" size="20" id="catalogId" name="catalogId" autocomplete="off" onkeyup="sendRequest()"> </td> <td><div id="validationMessage"></div></td> </tr> </table></form>

The preceding HTML uses the validationMessage div to display a validation message for the input field Catalog Id. The onkeyup event invokes a JavaScript sendRequest() function. The sendRequest() function creates an XMLHttpRequest object. The process of creating an XMLHttpRequest object differs depending on the browser implementation. If the browser supports the XMLHttpRequest object as a window property (all common browsers do except IE 5 and 6), the code can call the XMLHttpRequest constructor. If the browser implements the XMLHttpRequest object as an ActiveXObject object (as in IE versions 5 and 6), the code uses the ActiveXObject constructor. The function below calls an init() function, which checks to determine the appropriate creation method to use before creating and returning the object.

<script type="text/javascript"> function sendRequest(){ var xmlHttpReq=init(); function init(){ if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if (window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP"); } } </script>

Next, you need to initialize the XMLHttpRequest object using the open() method, specifying the HTTP method and the server URL to use.

var catalogId=encodeURIComponent( document.getElementById("catalogId").value); xmlHttpReq.open("GET", "validateForm?catalogId=" + catalogId, true);

HTTP requests sent with XMLHttpRequest are asynchronous by default, but you can explicitly set the async parameter true as shown above.

In this case, the call to the URL validateForm invokes a servlet on the server side, but you should recognize that the server-side technology is immaterial; the URL might actually be an ASP, ASP.NET, or PHP page, or a Web service—it doesn't matter as long as the page returns a response indicating whether the CatalogID value is valid. Because you're making an asynchronous call, you need to register a callback event handler that the XMLHttpRequest object will invoke when its readyState value changes. Remember that a change to the readyState value fires a readystatechange event. You register the callback event handler using the onreadystatechange property.


Next, we need to send the request using the send() method. Because this request uses the HTTP GET method, you can invoke send() method without an argument or null argument.


Processing a Request
In this example, because the HTTP method is GET, the receiving servlet on the server invokes a doGet() method, which retrieves the catalogId parameter value specified in the URL, and checks its validity against a database.

The servlet needs to construct a response to be sent to the client. This example returns XML, so it sets the HTTP content type of the response to text/xml and the Cache-Control header to no-cache. Setting the cache-control header prevents the browser from simply reloading the page from the cache.

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... ... response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); }

The response from the server is an XML DOM object. Create an XML string that contains instructions to be processed on the client side. The XML string must have a root element.


The XMLHttpRequest object is designed to handle responses consisting of plain text or XML; but a response may be of another type if the user agent (UA) supports the content type.

The XMLHttpRequest object calls the event handler registered with onreadystatechange when the request state changes. Therefore, your event handler should check the readyState value and the HTTP status before processing the response. When the request has completed loading, which corresponds to readyState value 4, and the HTTP status is "OK," the response has completed, and you can invoke a JavaScript function to process the response content. The following script checks the values and invokes a processResponse() method when the response is complete.

function processRequest(){ if(xmlHttpReq.readyState==4){ if(xmlHttpReq.status==200){ processResponse(); } } }

The processResponse() method uses the XMLHttpRequest objects' responseXML and responseText properties to retrieve the HTTP response. As explained above, the responseXML is available only if the media type of the response is text/xml, application/xml or ends in +xml. The responseText property returns the response as plain text. For an XML response you would retrieve the content as follows.

var msg=xmlHttpReq.responseXML;

With the XML stored in the msg variable, you can retrieve the element's value using the DOM method getElementsByTagName():

var catalogId=msg.getElementsByTagName( "catalogId")[0].firstChild.nodeValue;

Finally, you can test the element value to create a message that you display by updating the HTML content of the validationMessage div on the Web page, using the innerHTML property:

if(catalogId=="valid"){ var validationMessage = document.getElementById("validationMessage"); validationMessage.innerHTML = "Catalog Id is Valid"; } else { var validationMessage = document.getElementById("validationMessage"); validationMessage.innerHTML = "Catalog Id is not Valid"; }

That's the full cycle. The XMLHttpRequest object provides dynamic interaction between a client and a server by transferring data without posting the Web page to the server. You use JavaScript to launch a request and process the return value, and then you use browser DOM methods to update data on the page.

Deepak Vohra is an O'Reilly technical reviewer, who reviewed the book WebLogic: The Definitive Guide. He's also a NuBean consultant and web developer, and is a Sun Certified Java 1.4 Programmer and Sun Certified Web Component Developer for J2EE.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date