12. XMLHttpRequest (XHR)

XMLHttpRequest, or XHR, is a technology used by interactive web applications to make web requests to a server without causing page transitions.

12.1 Introduction

In traditional web applications, the browser renders a series of HTML pages which directly result from  server operations. This is essentially a more sophisticated version of the 'dumb terminal' models used by earlier mainframe applications.

Each time a user enters some data and submits a form, the browser makes a call to the server so that it can perform some operation or calculation. The results of that call are rendered in HTML and displayed as a new page:

Traditional Web Application

The use of XmlHttpRequest allows JavaScript on a web page to issue requests to a server without ever leaving the page. Modern, interactive web applications use this technique to update the web page without causing the distracting flicker that is seen when the browser loads a new page.

A typical example might be a shopping site with a cart that can be updated without leaving the page:

XHR Web Application

The data returned from an XHR call does not have to be in HTML format because it is not automatically rendered by the browser. Instead, it is parsed in JavaScript and appropriate changes are made to elements on the page to display the data.

In most cases, the JSON (JavaScript Object Notation) data format is used to transmit data to and from the server. It has a simple format and can be easily handled in JavaScript code.

12.2 Making an XHR call

All modern browsers support the use of the XmlHttpRequest object. The sample code, shown below, makes a call to the web server to obtain the data to display in a list box. The response data is in HTML format for the sake of simplicity because it allows the text returned from the server to be applied directly to the <div> tag.

<script type="text/javascript">			
function GetShoppingList()
{
    // Create an instance of the HTTP request object
    var xmlHttp = new XMLHttpRequest();

	// Register a callback that will handle the asynchronous response
	// from the server
	xmlHttp.addEventListener("load", function()
	{
		var targetNode = document.getElementById("divShoppingList");

		// Use the HTML returned from server to create list
		targetNode.innerHTML = xmlHttp.responseText;		
	});

    // Specify HTTP GET by default and supply the relative url
    xmlHttp.open("GET", "getlist.aspx");
    
    // Start an  asynchronous XHR request 
    xmlHttp.send();
}				
</script>

<form>
    <input onclick="GetShoppingList();"type="button" value="Fetch List"/>
    <div id="divShoppingList"></div>
</form>

A working demonstration of this code is shown below in Example 12

Example 12

Populate a List Box using AJAX

Click on 'Fetch List' to download a shopping list from the server:

12.3 Sending Parameters with XHR

XHR is often styled as an API call in which some kind of parameter list is constructed for a server-side call and the results are returned in a convenient format such as JSON.

There are two methods used for sending parameters. The first is to encode the parameters as query string values in the URL and the second is to use formatted data in the request body of a POST message.

Passing parameters in the request body is preferred when the data may be too large to fit in the request URL or where more the data has a more complex structure.

The code below shows how two numeric parameters can be passed to a server using  a simple comma delimited format. The encoded parameters are supplied as a string parameter to the send method and become the payload of the resulting HTTP POST request message:

<script type="text/javascript">
function AddNumbers()
{
    // Create an instance of the HTTP Request Object
    var xmlHttp = new XMLHttpRequest();

	// Register a callback that will handle the asynchronous response
	// from the server
	xmlHttp.addEventListener("load", function()
	{
		var result = document.getElementById("spanResult");

		// Use result of calculation from server
		result.innerHTML = xmlHttp.responseText;	
	});

    var value1 = document.getElementById("txtValue1").value;
    var value2 = document.getElementById("txtValue2").value;

    // Specify HTTP POST so that parameters can be passed in
    // request body
    xmlHttp.open("POST", "add.aspx");

    // Send the parameters in CSV format
    xmlHttp.send(value1 + "," + value2);
}
</script>

<form>
    <input id="txtValue1"/>
    <input id="txtValue2"/>
    <input onclick="AddNumbers();"type="button" value="Add"/>

    <p>Result:</p>
    <span id="spanResult"></span>
</form>

Example 13 shows a working version of this code:

Example 13

Pass two parameters with AJAX

Click on 'Add' to display the sum of the two numbers entered:

Result is:

Using HttpWatch with Examples 12 & 13

HttpWatch will show the XHR requests made by the demos on this page:

  1. Open HttpWatch by right clicking on the web page and selecting HttpWatch from the context menu
  2. Click on Record to start logging requests in HttpWatch
  3. Use the Examples 12 - 13 to see how XHR requests are recorded in HttpWatch
<  11. HTTPS

Ready to get started? TRY FOR FREE Buy Now