Using the XMLHttpRequest Object

Contact Us or call 1-877-932-8228
Using the XMLHttpRequest Object

Using the XMLHttpRequest Object

Now we're ready to do something with the data returned. Before looking at an example, let's take a look at the properties and methods of the xmlhttp object, so we know what's available to us.

XMLHttpRequest Object Properties
Property Description
onreadystatechange Specifies the callback function to be triggered when the ready state changes.
readyState Holds the state of the response.
responseText Holds the message body as a string.
responseXML Holds the message body as an XML object.
status Holds the status code returned from the server (e.g, 200 for success, 404 for page not found, etc.).
statusText Holds the status text returned from the server.
XMLHttpRequest Object Methods
Method Description
abort() Aborts the xmlhttp request.
getAllResponseHeaders() Retrieves the values of all the HTTP headers as a string.
getResponseHeader(header) Retrieves the value of the specified HTTP header as a string.
open(Method,URL,Async) Initializes the XMLHttpRequest object.
send(postData) Sends the HTTP request to the server.
setRequestHeader(header,value) Specifies the name and value of an HTTP header.

A common application is to check the status property to make sure that the request was successful (200) and then to output the message body to a div on the HTML page. The following sample file demonstrates this. To run the demo, first start the Node.js server:

  1. Open the command line (on a PC) or terminal (on a Mac), and navigate to the directory XHR/Demos/.
  2. Type npm install.
  3. Type npm start to start the Node.js server.

With the server started, you can then browse to http://localhost:8080/UsingXMLHttpRequest-Get.html to view the page.

Code Sample:

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

	function start() {
		var xmlhttp = new XMLHttpRequest();
		var contentDiv = document.getElementById("Content");"GET", "Demo?FirstName=Nat&LastName=Dunn", true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				contentDiv.innerHTML = xmlhttp.responseText;
---- C O D E   O M I T T E D ----

Code Explanation

This page simply "copies" the response text (xmlhttp.responseText) and "pastes" it into the "Content" div on the page.