The XMLHttpRequest Object


With the XMLHttpRequest object you can update parts of a web page, without reloading the whole page.


The XMLHttpRequest Object

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

The XMLHttpRequest object is the 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

Create an XMLHttpRequest Object

All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

xmlhttp=new XMLHttpRequest();

Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

To handle all modern browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object, if not, create an ActiveXObject:

Example

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

Try it yourself »


Send a Request To a Server

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:

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

Method Description
open(method,url,async) Specifies the type of request, the URL, and if the request should be handled asynchronously or not.

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) Sends the request off to the server.

string: Only used for POST requests


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("myDiv").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("myDiv").innerHTML=xmlhttp.responseText;

Try it yourself »


Server Response

To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object.

Property Description
responseText get the response data as a string
responseXML get the response data as XML data


The responseText Property

If the response from the server is not XML, use the responseText property.

The responseText property returns the response as a string, and you can use it accordingly:

Example

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

Try it yourself »


The responseXML Property

If the response from the server is XML, and you want to parse it as an XML object, use the responseXML property:

Example

Request the file cd_catalog.xml and parse the response:

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

Try it yourself »


The onreadystatechange event

When a request to a server is sent, we want to perform some actions based on the response.

The onreadystatechange event is triggered every time the readyState changes.

The readyState property holds the status of the XMLHttpRequest.

Three important properties of the XMLHttpRequest object:

Property Description
onreadystatechange Stores a function (or the name of a function) to be called automatically each time the readyState property changes
readyState Holds 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
status 200: "OK"
404: Page not found

In the onreadystatechange event, we specify what will happen when the server response is ready to be processed.

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

Example

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }

Try it yourself »

Note: The onreadystatechange event is triggered four times, one time for each change in readyState.


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.



Color Picker

colorpicker