devxlogo

A Detailed Explanation of the XMLHttpRequest Object

A Detailed Explanation of the XMLHttpRequest Object

synchronous JavaScript and XML (AJAX ) is a term for the process of transferring data between a client script and the server. The advantage of this is that it provides developers with a way to retrieve content from a Web server without posting the page the user is currently viewing to the server. In concert with modern browsers’ ability to dynamically change displayed content through programming code (JavaScript) that accesses the browser’s DOM, AJAX lets developers update the HTML content displayed in the browser without refreshing the page. In other words, AJAX can make browser-based applications more interactive, more responsive, and more like traditional desktop applications.

Google’s Gmail and Outlook Express are two familiar examples that use AJAX techniques. AJAX may be used with any client-side scripting language, including JavaScript, JScript, and VBScript.

AJAX takes advantage of an object built into all modern browsers?-the XMLHttpRequest object?to send and receive HTTP requests and responses. An HTTP request sent via the XMLHttpRequest object does not require the page to have or post a

element. The ‘A’ in AJAX stands for “asynchronous,” which means that the XMLHttpRequest object’s send() method returns immediately, letting the browser processing of other HTML/JavaScript on the Web page continue while the server processes the HTTP request and sends the response. While asynchronous requests are the default, you can optionally send synchronous requests, which halts other Web page processing until the page receives the server’s response.

Microsoft introduced the XMLHttpRequest object as an ActiveX object in Internet Explorer (IE) 5. Other browser manufacturers, recognizing the object’s utility, implemented the XMLHttpRequest object in their browsers, but as a native JavaScript object rather than as an ActiveX object. In turn, recognizing the value and security in that implementation type, Microsoft has recast the XMLHttpRequest in IE 7 as a window object property. Fortunately even when the implementation (and thus invocation) details differ, all the browsers’ implementations have similar functionality and essentially identical methods. The W3C is working to standardize the XMLHttpRequest object, releasing a working draft of the W3C specification

This article discusses the XMLHttpRequest object API in detail, listing and explaining all the properties and methods.

XMLHttpRequest Object Properties and Events
The XMLHttpRequest object exposes various properties, methods, and events so script can process and control HTTP requests and responses. The rest of this article discusses these in detail.

The readyState Property
The XMLHttpRequest object cycles through several states as it sends an HTTP request to the server, waits while the request is processed, and when it receives a response. So that scripts can respond appropriately to the various states, the object exposes a readyState property that represents the object’s current state, as shown in Table 1.

Table 1. The XMLHttpRequest Object’s ReadyState Property Values: The table shows the possible values of the readyState property and an explanation of each.

ReadyState ValueDescription
0Represents an “uninitialized” state in which an XMLHttpRequest object has been created, but not initialized.
1Represents a “sent” state in which code has called the XMLHttpRequest open() method and the XMLHttpRequest is ready to send a request to the server.
2Represents a “sent” state in which a request has been sent to the server with the send() method, but a response has not yet been received.
3Represents a “receiving” state in which the HTTP response headers have been received, but message body has not yet been completely received.
4Represents a “loaded” state in which the response has been completely received.

The onreadystatechange Property
The XMLHttpRequest object fires a readystatechange event whenever the readyState value changes. The onreadystatechange property accepts an EventListener value, specifying the method that the object will invoke whenever the readyState value changes.

The responseText Property
The responseText property contains the text of the HTTP response received by the client. When the readyState value is 0, 1, or 2 responseText contains an empty string. When the readyState value is 3 (Receiving), the response contains the incomplete response received by the client. When readyState is 4 (Loaded) the responseText contains the complete response.

The responseXML Property
The responseXML property represents the XML response when the complete HTTP response has been received (when readyState is 4), when the Content-Type header specifies the MIME (media) type as text/xml, application/xml, or ends in +xml. If the Content-Type header does not contain one of these media types, the responseXML value is null. The responseXML value is also null whenever the readyState value contains any value other than 4.

The responseXML property value is an object of type Document interface, and represents the parsed document. If the document cannot be parsed (for example if the document is malformed or the character encoding of the document is not supported) the responseXML value is null.

The status Property
The status property represents the HTTP status code and is of type short. The status attribute is available only when the readyState value is 3 (Receiving) or 4 (Loaded). Attempting to access the status value when readyState is less than 3 raises an exception.

The statusText Property
The statusText attribute represents the HTTP status code text and is also available only when the readyState value is 3 or 4. Attempting to access the statusText property for other readyState values raises an exception.

XMLHttpRequest Object Methods
The XMLHttpRequest object provides various methods to initiate and process HTTP requests, listed alphabetically and discussed in detail in the following sections.

The abort() Method
You use the abort() method halt the HTTP request associated with an XMLHttpRequest object to reset the object to the uninitialized state

The open() Method
You call the open(DOMString method, DOMString uri, boolean async, DOMString username, DOMString password) method to initialize an XMLHttpRequest object. The method parameter is required and specifies the HTTP method (GET, POST, PUT, DELETE, or HEAD) that you want to use to send the request. To send data to the server, use the POST method. To retrieve data from the server, use the GET method. The uri parameter specifies the server URI to which the XMLHttpRequest object sends the request. The uri resolves to an absolute URI using the window.document.baseURI property?in other words, you can use relative URIs which will be resolved in the same way that the browser resolves relative URIs. The async parameter specifies whether the request is asynchronous; the default value is true. To send a synchronous request, set the parameter to false. For servers that require authentication, you can supply the optional username and password parameters. After calling the open() method, the XMLHttpRequest objects sets its readyState property to 1 (Open) and resets the responseText, responseXML, status, and statusText properties to their initial values. It also resets the request headers. Note that the object resets these values if you call the open() method when readyState is 4.

The send() Method
After preparing a request by calling the open() method, you send the request to the server. You may call send() only when the readyState value is 1, otherwise the XMLHttpRequest object raises an exception. The request gets sent to the server using the parameters supplied to the open() method. The send() method returns immediately when the async parameter is true, letting other client script processing continue. The XMLHttpRequest object sets the readyState value to 2 (Sent) after the send() method has been called. When the server responds, before receiving the message body, if any, the XMLHttpRequest object sets readyState to 3 (Receiving). When the request has completed loading it sets readyState to 4 (Loaded). For a request of type HEAD, it sets the readyState value to 4 immediately after setting it to 3.

The send() method takes an optional parameter that may contain data of varying types. Typically, you use this to send data to the server using the POST method. You can explicitly invoke the send() method with null, which is the same as invoking it with no argument. For most other data types, set the Content-Type header using the setRequestHeader() method (explained below) before invoking the send() method. If the data parameter in the send(data) method is of type DOMString, encode the data as UTF-8. If data is of type Document, serialize the data using the encoding specified by data.xmlEncoding, if supported or UTF-8 otherwise.

The setRequestHeader() Method
The setRequestHeader(DOMString header, DOMString value) method sets request headers. You may call this method after calling the open() method?when the readyState value is 1?otherwise you’ll get an exception.

The getResponseHeader() Method
You use getResponseHeader(DOMString header, value) method used to retrieve response header values. Call getResponseHeader() only when the readyState value is 3 or 4 (in other words, after the response headers are available); otherwise, the method returns an empty string.

The getAllResponseHeaders() Method
The getAllResponseHeaders() method returns all the response headers as a single string with each header on a separate line. The method returns null if readyState value is not 3 or 4.

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.

      
Catalog Id:

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.

 

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.

   xmlHttpReq.onreadystatechange=processRequest;

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.

   xmlHttpReq.send(null);  

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.

   out.println("valid");
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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist