XMLHttpRequest Object
Using the XMLHttpRequest object, you can update a part of a web page without reloading the entire page.
XMLHttpRequest Object
The XMLHttpRequest object is used to exchange data with a server behind the scenes.
The XMLHttpRequest object is a developer's dream, because you can:
- Update the web page without reloading the page
- Request data from the server after the page has loaded
- Receive data from the server after the page has loaded
- Send data to the server in the background
Creating an XMLHttpRequest Object
All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
Older versions of Internet Explorer (IE5 and IE6) use an ActiveX object:
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 ActiveX object:
Example
if (window.XMLHttpRequest) {
// Code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// Code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
Sending a Request to the Server
To send a request to the server, we use the open() and send() methods of the XMLHttpRequest object:
Method | Description |
---|---|
open(method, url, async) | Specifies the type of request, the URL, and if the request should be handled asynchronously. <br> <br> method: The type of request: GET or POST <br> url: The location of the file on the server <br> async: true (asynchronous) or false (synchronous) |
send(string) | Sends the request to the server. <br> <br> 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:
- Caching files is not an option (updating files or databases 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
URL - File on the Server
The url parameter of the open() method is an address of a file on the server:
This file can be of any type (such as .txt and .xml), or a server script file (such as .html and .php, which can perform actions on the server before sending back a response).
Asynchronous - True or False?
To send the request asynchronously, the async parameter of the open() method must be set to true:
Sending asynchronous requests is a huge advancement for web developers. Many tasks performed on the server are very time-consuming.
By sending asynchronously, JavaScript does not have to wait for the server's response but can instead:
- Execute other scripts while waiting for the server's response
- Handle the response when it 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();
Async=false
To use async=false, change the third parameter of the open() method to false:
Using async=false is not recommended, but it can be used for small requests.
Remember, 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 using async=false, do not write an onreadystatechange function - just place the code after the send() statement:
Example
xmlhttp.open("GET", "xmlhttp_info.txt", false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
Server Response
To get the response from the server, use the responseText or responseXML property of the XMLHttpRequest object.
Property | Description |
---|---|
responseText | Get the response data as a string |
responseXML | The responseXML property returns the XML document object, which can be examined and parsed using DOM node tree methods and properties. |
responseText Property
If the response from the server is not XML, use the responseText property.
The responseText property returns the response as a string, which you can use accordingly:
Example
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
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;
onreadystatechange Event
When a request is sent to the server, we need 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: <br>0: Request not initialized <br>1: Server connection established <br>2: Request received <br>3: Processing request <br>4: Request finished and response is ready |
status | 200: "OK" <br>404: Page not found |
In the onreadystatechange event, we specify what happens when the server response is ready.
When readyState is 4 or status is 200, the response is ready:
Example
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
};
Note: The onreadystatechange event is triggered four times (1-4) each time the readyState changes.
More Examples
Retrieve header information with getAllResponseHeaders()
Retrieve specific header information with getResponseHeader()
Retrieve the content of an ASP file