11. AJAX
AJAX is a technology used by interactive web applications to make HTTP 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:
The use of AJAX allows JavaScript on a web page to issue HTTP 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:
The data returned from an AJAX 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 page to display the data.
AJAX stands for Asynchronous JavaScript And XML because early implementations often used XML as the data format. Since then, simpler more efficient formats such as JSON (JavaScript Object Notation) have gained popularity.
12.2 Making an AJAX call
The core functionality of AJAX is implemented in the XmlHttpRequest object that is now incorporated in most modern browsers. 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();
// Specify HTTP GET by default and supply the relative url
xmlHttp.open("GET", "getlist.aspx", false);
// Start a synchronous AJAX request and wait
// for the response
xmlHttp.send(null);
var targetNode = document.getElementById("divShoppingList");
// Use the HTML returned from server to create list
targetNode.innerHTML = xmlHttp.responseText;
}
</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 AJAX
AJAX is often styled as an RPC mechanism 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 XML, CSV or JSON.
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();
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", false);
// Send the parameters in CSV format
xmlHttp.send(value1 + "," + value2);
var result = document.getElementById("spanResult");
// Use result of calculation from server
result.innerHTML = xmlHttp.responseText;
}
</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:
12.4 Using AJAX with a JavaScript Library
There are a number of issues with AJAX that have been ignored in the previous sections:
- Some older browsers do not natively support the XmlHttpRequest object. For example, in IE 6 you have to use ActiveXObject("Msxml2.XMLHTTP") to create an XmlHttpRequest object.
- Any use of AJAX requires error handling code so that meaningful errors are displayed to the user. This is not a straightforward task because the server may return success codes other than '200 OK', or different classes of failure.
- AJAX calls can be made asynchronously so that the web application remains responsive even if a call to the server takes several seconds. Handling this asynchronous mode of operation is fairly involved as it requires the use of a callback function and querying the value of the readystate property.
Given these challenges most developers use a library to handle the cross-browser issues and simplify what is essentially 'boilerplate' code. One of the most widely used is jQuery which provides AJAX support as well as many other features.
Let's see how we could re-work one of our earlier examples using jQuery. Almost any HTML element can be the target recipient of an AJAX request in jQuery a. If our server returns HTML we can simply bind our <div> output tag directly as shown below:
function jQueryGetShoppingList()
{
// $ could be used as an alias for jQuery:
//
// $("#divShoppingList").load("getlist.aspx");
//
jQuery("#divShoppingList").load("getlist.aspx");
}
Example 14 shows a working version of this code:
Example 14
Populate a List Box using AJAX and jQuery
Click on 'Fetch List' to download a shopping list from the server::
Using HttpWatch with Examples 12, 13 & 14
HttpWatch will show the AJAX requests made by the demos on this page:
- Open HttpWatch by right clicking on the web page and selecting HttpWatch from the context menu
- Click on Record to start logging requests in HttpWatch
- Use the Examples 12 - 14 to see how AJAX requests are recorded in HttpWatch