Skip to main content

XML DOM: XMLHttpRequest Object

The XMLHttpRequest object is used to exchange data with a server behind the scenes.

With XMLHttpRequest object you can:

  • Update a web page without reloading the page
  • Request data from a server after the page has loaded
  • Receive data from a server after the page has loaded
  • Send data to a server in the background

Properties

PropertyDescription
onreadystatechangeStores a function (or the name of a function) to be called automatically each time the readyState property changes
readyStateHolds the status of the XMLHttpRequest. Changes from 0 to 4: 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready
responseTextReturns the response data as a string
responseXMLReturns the response data as XML data
statusReturns the status-number (e.g. "404" for "Not Found" or "200" for "OK")
statusTextReturns the status-text (e.g. "Not Found" or "OK")

Methods

MethodDescription
abort()Cancels the current request
getAllResponseHeaders()Returns header information
getResponseHeader()Returns specific header information
open(method,url,async,uname,pswd)Specifies the type of request, the URL, if the request should be handled asynchronously or not, and other optional attributes of a request method: the type of request: GET or POST url: the location of the file on the server async: true (asynchronous) or false (synchronous)
send(string)send(string) Sends the request off to the server. string: Only used for POST requests
setRequestHeader()Adds a label/value pair to the header to be sent

Example

An XMLHttpRequest object can be instatiated as follows

xmlhttp = new XMLHttpRequest();

To handle all browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object as below:

if(window.XMLHttpRequest)  // for Firefox, IE7+, Opera, Safari, ... {
xmlHttp = new XMLHttpRequest();
} else if(window.ActiveXObject) // for Internet Explorer 5 or 6 {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}

Table of Contents