The XMLHttpRequest object

Contact Us or call 1-877-932-8228
The XMLHttpRequest object

The XMLHttpRequest object

Another important object that we use a lot in JavaScript these days is the XMLHttpRequest object. This is the object that powers the Ajax functionality in a lot of web pages.

This object is also not part of JavaScript. It can be used from JavaScript but it isn't part of the language.

The XMLHttpRequest object allows our scripts to initiate a request to a URL and collect the server response without the need to reload the entire page.

We will provide a video presentation on the XMLHttpRequest object later in this lesson.

Code Sample:

---- C O D E   O M I T T E D ----

window.onload = function() {
	var xmlhttp = new XMLHttpRequest();
	var headers;
	var output = document.getElementById("headers");
	var response = document.getElementById("response");
	var temp = "";"GET", "arrays.html", true);
	xmlhttp.onreadystatechange = function() {
		if ( this.readyState > 2 && typeof headers == "undefined" ) {
			headers = this.getAllResponseHeaders().split("\n");
			temp = "<ol>";
			for (var i in headers) {
				if (headers[i].trim().length > 0) {
					temp += "<li>" + headers[i] + "</li>";
			temp += "</ol>";
<output id="headers"></output>
<textarea id="response" cols="50" rows="20"></textarea>
---- C O D E   O M I T T E D ----

Note that this code will only work if it runs through a web server (e.g, http://localhost/JavaScript/ClassFiles/QuickRecap/Demos/xmlhttprequest.html), which you may not have configured locally. The image below shows how the page appears when run through a web server: Page through Web Server

As an aside, see XMLHttpRequest readyState bug in Opera for an explanation of why we use this.readyState > 2 && typeof headers == "undefined" instead of just this.readyState == 2.