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.
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:
A typical example might be a shopping site with a cart that can be updated without leaving the page:
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.
A working demonstration of this code is shown below in 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:
Example 13 shows a working version of this code:
Pass two parameters with AJAX
Click on 'Add' to display the sum of the two numbers entered:
Using HttpWatch with Examples 12 & 13
HttpWatch will show the XHR 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 - 13 to see how XHR requests are recorded in HttpWatch