The XMLHttpRequest
object is the foundation that makes Ajax possible with the back-end communication between browser and web server. Fortunately, all modern browsers now support the XMLHttpRequest
object.
Without the support for this object, the browser would not be able to exchange data with the web server and update parts of the page without reloading the entire page. With Ajax, we can make GET
and POST
HTTP requests. However, there are some limitations to XMLHttpRequest
object.
These are mainly for security reasons. First, this object can only make HTTP(S) requests. References to File URLs are not supported. Secondly, it can make requests only to the same domain as the currently loaded page. If XMLHttpRequest
allowed requests to any website, it could be used for malicious purposes.
Example
We will use the following HTML for the examples listed below.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// ... JavaScript code
</script>
</head>
<body>
<img id="img1" onclick="callFunction()" src="go.png" /> ;
<div id="div1"> <!-- Some Content --> </div>
</body>
</html>
Syntax
variable = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Safari, and Opera
variable = new ActiveXObject("MSXML2.XMLHTTP.6.0");
variable = new ActiveXObject("MSXML2.XMLHTTP.5.0");
variable = new ActiveXObject("MSXML2.XMLHTTP.4.0");
variable = new ActiveXObject("MSXML2.XMLHTTP.3.0");
variable = new ActiveXObject("MSXML2.XMLHTTP");
variable = new ActiveXObject("Microsoft.XMLHTTP");
To ensure that all browsers, including IE5 and IE6, will be supported, you first check if the browser supports the XMLHttpRequest
object. If it does, then create an XMLHttpRequest
object. If it does not, create an ActiveXObject
.
There have been several versions released with each subsequent release of the MSXML library. Each release brings with it better stability and speed, so you want to make sure you are always using the most recent version available on the user’s machine.
If you want to make sure that you are supported IE5, you will need to check against ActiveXObject("Microsoft.XMLHTTP")
. It isn’t necessary to check for each ActiveXObject
version. If you are not interested in supporting IE5, but you do want to support IE6, you could check back to MSXML2.XMLHTTP.3.0
.
XMLHTTPRequest Methods
Method | Description |
---|---|
abort() | Cancels the current request |
getAllResponseHeaders() | Returns header information |
getResponseHeader() | Returns specific header information |
open(method,url) | Specifies the method and URL (GET , POST , HEAD ) |
open(method,url,async) | The async parameter specifies whether the request async or sync; true = async, async is default |
open(method,url,async,userName) | Specifies the username to connect |
open(method,url,async,userName,password) | Specifies the password to connect |
send(string) | Sends the request off to the server |
setRequestHeader() | Adds a label/value pair to the header to be sent |
XMLHTTPRequest Properties
Property | Description |
---|---|
onreadystatechange | Function to be called when the readyState property changes |
readyState | Holds the status of the XMLHttpRequest , values from 0 – 4 |
responseText | Returns the response data as a string |
responseXML | Returns the response data as XML data |
status | Returns the status-number. 200-OK, 404-Not Found |
statusText | Returns the status-text: Ok, Not Found |
function loadAjax() {
var xhr = false;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
} else {
// IE5-IE6
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
Here is another method for creating the XMLHTTPRequest
object. You would call the function and check if the variable assigned is not NULL
. If it is NULL
, log the error or inform the user that the browser does not support the XMLHTTPRequest
object.
Using a try
or catch
block is a good idea when using ActiveXOjbects
because any failure to create an object will throw an error.
function getXMLHttpRequest() {
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
} else {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(ex) {
return null;
}
}
}
Here is a simple example that uses a combination of the recommendations provided so far. In this example, we attempt to create the native XMLHTTPRequest
object.
If we are not successful, we try to create the ActiveXObject
. If that is not successful, we catch the error.
Example
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadAjax() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new window.XMLHttpRequest;
} else {
try {
xhr = ActiveXObject("Microsoft.XMLHTTP");
} catch (ex) {
window.console.log("Ajax not supported.");
}
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "demo_ajax_load.txt", true);
xhr.send(null);
}
}
</script>
</head>
<body>
<img id="img1" src="#" onclick="loadAjax()" />
<div id="div1">Click the icon to load data via Ajax!</div>
</body>
</html>
Here is another way to write the JavaScript code. This approach organizes the various portions of the Ajax code into distinct functions.
<script type="text/javascript">
function loadAjax() {
var xhr = getXHR();
if (xhr != null) {
xhr.open("GET", "/demo/ajax_load.txt", true);
xhr.onreadystatechange = handler;
xhr.send();
} else {
window.console.log("Ajax not supported.");
}
function getXHR() {
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
}
else {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch (ex) {
return null;
}
}
}
function handler() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
}
}
</script>