FREE Web Template Download
HTML CSS JAVASCRIPT SQL PHP BOOTSTRAP JQUERY ANGULARJS TUTORIALS REFERENCES EXAMPLES Blog
 

The XMLHttpRequest Object


All modern browsers have a built-in XMLHttpRequest object to request data from a server.

All major browsers have a built-in XML parser to access and manipulate XML.


The XMLHttpRequest Object

The XMLHttpRequest object can be used to request data from a web server.

The XMLHttpRequest object is a developers dream, because 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

XMLHttpRequest Example

When you type a character in the input field below, an XMLHttpRequest is sent to the server, and some name suggestions are returned (from the server):

Example

Start typing a name in the input field below:

Name:

Suggestions:


Sending an XMLHttpRequest

All modern browsers have a built-in XMLHttpRequest object.

A common JavaScript syntax for using it looks much like this:

Example

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
       // Action to be performed when the document is read;
    }
};
xhttp.open("GET", "filename", true);
xhttp.send();
Try it Yourself »

Creating an XMLHttpRequest Object

The first line in the example above creates an XMLHttpRequest objet:

var xhttp = new XMLHttpRequest();

The onreadystatechange Event

The readyState property holds the status of the XMLHttpRequest.

The onreadystatechange event is triggered every time the readyState changes.

During a server request, the readyState 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

In the onreadystatechange property, specify a function to be executed when the readyState changes:

xhttp.onreadystatechange = function()

When readyState is 4 and status is 200, the response is ready:

if (xhttp.readyState == 4 && xhttp.status == 200)

XMLHttpRequest Properties and Methods

Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
open(method, url, async) Specifies the type of request
method: the type of request: GET or POST
url: the file location
async: true (asynchronous) or false (synchronous)
send() Sends a request to the server (used for GET)
send(string) Sends a request string to the server (used for POST)
onreadystatechange A function to be called when the readyState property changes
readyState The status of the XMLHttpRequest
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: OK
404: Page not found
responseText The response data as a string
responseXML The response data as XML data

Access Across Domains

For security reasons, modern browsers do not allow access across domains.

This means that both the web page and the XML file it tries to load, must be located on the same server.

The examples on subhodaya all open XML files located on the subhodaya domain.

If you want to use the example above on one of your own web pages, the XML files you load must be located on your own server.


The responseText Property

The responseText property returns the response as a string.

If you want to use the response as a text string, use the responseText property:

Example

document.getElementById("demo").innerHTML = xmlhttp.responseText;
Try it Yourself »

The responseXML Property

The responseXML property returns the response as an XML DOM object.

If you want to use the response as an XML DOM object, use the responseXML property:

Example

Request the file cd_catalog.xml and use the response as an XML DOM object:

xmlDoc = xmlhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
    txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
Try it Yourself »

GET or POST?

GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

  • A cached file is not an option (update a file or database on the server)
  • Sending a large amount of data to the server (POST has no size limitations)
  • Sending user input (which can contain unknown characters), POST is more robust and secure than GET

The url - A File On a Server

The url parameter of the open() method, is an address to a file on a server:

xmlhttp.open("GET", "xmlhttp_info.txt", true);

The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and .php (which can perform actions on the server before sending the response back).


Asynchronous - True or False?

To send the request asynchronously, the async parameter of the open() method has to be set to true:

xmlhttp.open("GET", "xmlhttp_info.txt", true);

Sending asynchronously requests is a huge improvement for web developers. Many of the tasks performed on the server are very time consuming.

By sending asynchronously, the JavaScript does not have to wait for the server response, but can instead:

  • execute other scripts while waiting for server response
  • deal with the response when the response is ready

Async = true

When using async = true, specify a function to execute when the response is ready in the onreadystatechange event:

Example

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
       document.getElementById("demo").innerHTML = xmlhttp.responseText;
    }
};
xmlhttp.open("GET", "xmlhttp_info.txt", true);
xmlhttp.send();
Try it Yourself »

Async = false

To use async = false, change the third parameter in the open() method to false:

xmlhttp.open("GET", "xmlhttp_info.txt", false);

Using async = false is not recommended, but for a few small requests this can be ok.

Remember that the JavaScript will NOT continue to execute, until the server response is ready. If the server is busy or slow, the application will hang or stop.

Note: When you use async = false, do NOT write an onreadystatechange function - just put the code after the send() statement:

Example

xmlhttp.open("GET", "xmlhttp_info.txt", false);
xmlhttp.send();
document.getElementById("demo").innerHTML = xmlhttp.responseText;
Try it Yourself »

XML Parser

All modern browsers have a built-in XML parser.

The XML Document Object Model (the XML DOM) contains a lot of methods to access and edit XML.

However, before an XML document can be accessed, it must be loaded into an XML DOM object.

An XML parser can read plain text and convert it into an XML DOM object.


Parsing a Text String

This example parses a text string into an XML DOM object, and extracts the info from it with JavaScript:

Example

<html>
<body>

<p id="demo"></p>

<script>
var text, parser, xmlDoc;

text = "<bookstore><book>" +
"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book></bookstore>";

parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");

document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
</script>

</body>
</html>
Try it Yourself »

Old Browsers (IE5 and IE6)

Old versions of Internet Explorer (IE5 and IE6) do not support the XMLHttpRequest object.

To handle IE5 and IE6, check if the browser supports the XMLHttpRequest object, or else create an ActiveXObject:

Example

if (window.XMLHttpRequest) {
    // code for modern browsers
    xmlhttp = new XMLHttpRequest();
 } else {
    // code for old IE browsers
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
Try it Yourself »

Old versions of Internet Explorer (IE5 and IE6) do not support the DOMParser object.

To handle IE5 and IE6, check if the browser supports the DOMParser object, or else create an ActiveXObject:

Example

if (window.DOMParser) {
  // code for modern browsers
  parser = new DOMParser();
  xmlDoc = parser.parseFromString(text,"text/xml");
} else {
  // code for old IE browsers
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async = false;
  xmlDoc.loadXML(text);
Try it Yourself »

Examples

More Examples

Retrieve header information with getAllResponseHeaders()
Retrieve header information of a resource (file).

Retrieve specific header information with getResponseHeader()
Retrieve specific header information of a resource (file).

Retrieve the content of an ASP file
How a web page can communicate with a web server while a user type characters in an input field.

Retrieve content from a database
How a web page can fetch information from a database with the XMLHttpRequest object.

Retrieve the content of an XML file
Create an XMLHttpRequest to retrieve data from an XML file and display the data in an HTML table.