logo
header art

Getting Started with Ajax

June 23, 2005

Part 1: Simple Ajax Example
To get started with Ajax, we will focus on the client side Javascript and how to use the XMLHttpRequest object with various browsers. In this example, we will create a simple web page that retrieves notes from the server and displays them in a DIV without refreshing the page.
Opening a Connection in Javascript
The exciting thing about Ajax is its ability to open new connections, request information, and usefully process responses from within Javascript without having to reload the entire page. The xmlOpen(...) Javascript function is a browser-agnostic wrapper of various XMLHttpRequest implementations. It performs necessary browser checks, opens a connection to the specified url, transmits data, and registers responseHandler as a listener to the readyStateChanged event. xmlOpen(...) is located in pages/exampleutils.js and is used in all of the examples in this article.

Note that browser security settings may prevent connections to third-party web sites. Therefore, the url parameter to xmlOpen(...) should reference the same domain as the one used to serve the original page. For example, if the web page using this function is http://www.skillfusion.com/part1.html then url should also reference some resource at http://www.skillfusion.com/....

The following is the source code for xmlOpen(...)
01 /**
02  * Open a connection to the specified URL, which is
03  * intended to respond with an XML message.
04  
05  @param string method The connection method; either "GET" or "POST".
06  @param string url    The URL to connect to.
07  @param string toSend The data to send to the server; must be URL encoded.
08  @param function responseHandler The function handling server response.
09  */
10 function xmlOpen(method, url, toSend, responseHandler)
11 {
12     if (window.XMLHttpRequest)
13     {
14         // browser has native support for XMLHttpRequest object
15         req = new XMLHttpRequest();
16     }
17     else if (window.ActiveXObject)
18     {
19         // try XMLHTTP ActiveX (Internet Explorer) version
20         req = new ActiveXObject("Microsoft.XMLHTTP");
21     }
22     
23     if(req)
24     {
25         req.onreadystatechange = responseHandler;
26         req.open(method, url, true);
27         req.setRequestHeader("content-type","application/x-www-form-urlencoded");
28         req.send(toSend);
29     }
30     else
31     {
32         alert('Your browser does not seem to support XMLHttpRequest.');
33     }
34 }
Lines 12-21 of xmlOpen(...) perform necessary browser checks and instantiate a new request object for either browser type. Since the Mozilla/Gecko XMLHttpRequest object is similar to the ActiveX XMLHTTP object, we are able to re-use lines 23-33 for all supported browsers. This block of code performs the following connection related tasks:
  1. It registers the function referenced by responseHandler as a listener to the readyStateChange event, i.e., the function passed in as responseHandler will be executed when the request object's ready-state changes.
  2. It asynchronously opens a connection to url with the specified HTTP method (POST or GET). Opening the connection synchronously is highly discouraged since it is possible to never receive a response from the server, causing the browser to lock up.
  3. It sets the content-type to application/x-www-form-urlencoded (default for an HTML form) and trasmits toSend. Note that no encoding of toSend is done in this function so the caller is responsible for encoding it as a URL.
In addition to xmlOpen(...), pages/exampleutil.js contains a few other useful functions, two of which are xmlGet(...) and xmlPost(...). These functions are simple wrappers to xmlOpen(...) that supply the relevant value for the method parameter. xmlGet(...) passes null as the toSend parameter to xmlOpen(...) since it is not transmitting any extra information.