Creating a dynamic, user-friendly website interface is simple and straightforward
by Andrew Turner
Introduction
Modern websites and web-applications appear drastically different
from sites on the web 5 and 10 years ago. Tools like GoogleMail,
BaseCamp, and TiddlyWiki have revolutionized the general concept of
what a webpage can do and how users interact with it. The days of
clicking on a simple hyperlink to be taken to a new page, or sitting
and waiting for a form submission are rapidly dwindling.
The technology driving these sites is not really new, but
their application and use has only recently become widespread and
supported by a majority of web browsers. Furthermore, many web
developers feel daunted by the rapid pace of the changing techniques
and don't have a clear understanding of how the technologies are
implemented and used.
One of the most revolutionizing of these technologies has been
dubbed AJAX (or Ajax depending upon whom you ask). Ajax is responsible
for dynamic page content, marking database entries, and in-line
text-editing without the need for page-reloads or large, complex
plug-ins like Flash or Java.
The goal of this article is to teach you the basics of Ajax
and demonstrate that it is not as difficult a concept as it may first
appear. In reality, Ajax is simple and easy for any web developer to
add to their new or already existing site.
What is Ajax?
AJAX is an acronym for: Asynchronous Javascript and XML. The most
important concept of AJAX is the "asynchronous" part. Asynchronous
communication means that commands do not need to wait for a response.
By contrast, synchronous communication requires the command to wait for
a response before continuing. An example of synchronous communication
is a typical hyperlink; the user clicks a link, and then waits while
the resulting page is requested, returned, and displayed. An
asynchronous example may be having a contact name and phone number
lookup with dynamic autocomplete with names already in the database.
For application developers, it may be useful to think of synchronous
communication as modal, while asynchronous is non-modal.
Javascript is the client-side scripting language that has been
used to implement the input, output and server-response handling.
Because the code is client-side it is fast and scales up with
increasing usage. The last part of the AJAX acronym is XML (extensible
Markup Language), which is used in the response to encapsulate
information. By using a structure like XML, the client can parse the
tree for specific data without having a predetermined order of the
data. As we will discuss, XML or Javascript are not required to
implement "Ajax" in a site.
Ajax uses several other technologies and functionality to work.
XHTML and the Document Object Model (DOM) allow Javascript to
dynamically modify a webpage. CSS (Cascading Style Sheets) are not
necessary, but are typically employed to provide for easy layout and
design of a webpage and allow the Ajax functionality to work on the
data, and not the view.
The reason the technology is referred to as either AJAX or
Ajax is because of the blurring between the concept, and the
implementation. Ajax (non-acronym) has become the terminology
associated with the ability to dynamically modify a webpage or backend
content without requiring a page reload, while AJAX (acronym) is the
specific implementation of Ajax employing Javascript and XML. The term
Ajax was coined by Jesse Garnett of AdaptivePath (see resources) as a
better name than the previously used "Asynchronous JavaScript + CSS +
DOM + XMLHttpRequest". The technologies were all originally combined by
Microsoft for developing their Outlook Personal Information Manager
(PIM) web application interface.
Why use Ajax?
While the web has inarguably drastically changed the way a computer
user works, to date they haven't been able to fully replace, or even
work entirely in tandem with, desktop applications. To clarify, a
desktop application is software that must be installed on a user's
computer and is run in a self-contained window/context. By contrast, a
web application operates primarily within a user's browser and is not
required to be installed on a machine. This provides users access to
the application and associated data from any computer using a suitable
browser.
However, with the advent and widespread use of technologies
such as Ajax, users can now complement, or even replace, their desktop
applications with a web application. Many users are now switching to
reading their email in GoogleMail, storing their documents and notes in
TiddlyWiki, reading their RSS news via Gregarious, or working with
colleagues in BaseCamp.
Adding Ajax to your own web site or web application provides a
much smoother, and rich user experience. Furthermore, Ajax websites
more closely imitate their desktop counterparts, allowing users to
interact and understand the user interfaces in a similar way.
Ajax is also a relatively straightforward and simple
technology to provide in a website. Developers may quickly become
confused by all of the terms, techniques, and options. However, at its
core, Ajax is quick to setup and begin using, and completely flexible
for whatever the developer and site requirements need. Ajax can be used
for features such as inline form validation, database queries, content
editing, drag-and-drop, page updating, and many others
Setting up the framework
Parts of Asynchronous Communications
In order to understand the essential parts of an Ajax framework, we
will discuss the necessary parts of asynchronous communications. The
parts are split up by Client, the user's browser, and Server, the
website hosting server.
Client: Create a request object
BClient: Assign a response handler
Client: Send a query to the server
Server: Receive the query, and perform operations
Server: Send the response to the client
Client: Handle the server response

Figure
1: Asynchronous communications allow a user to continually interact
with the browser, and provides dynamic updating of the web site
The client requests to the server can happen continually, updating
the web page or application on each response received. Each request
happens separately from the interface, allowing the user to continue to
view and interact with the web page.
However, it is a good idea to only support a single
asynchronous command at a time as the response may affect the interface
data. If multiple asynchronous requests are supported, you must be
careful to handle potential conflicts due to user interaction with
outdated data.
Create a request object
The first thing to do is to create a constructor that will build a
client-side request object. A request object is responsible for
wrapping up the actual request, response handler, and state of the
request.
Remember that this Javascript code is being run on the user's
desktop browser. Therefore creating the request object is the one place
where browser specific code is required. In this case, Microsoft's
Internet Explorer uses an ActiveX object as the request object, whereas
the other browsers all support an XMLHttpRequest() constructor call. We
can interrogate the browser to find out what type it is and create the
appropriate object. This function is universal for any Ajax use.
AjaxFramework.js
// request object constructor
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
You should now create a global request object that will be used by the client for all future communication.
AjaxFramework.js
// global request object
var http = createRequestObject();
Assign a response handler and handle the response
Our second step is to assign a response handler. A handler is the
function that will be called when the request comes back from the
server to the client's computer. This function is responsible for
verifying the state of the answer, and parsing the response as
appropriate. This function is implemented on a project specific basis.
It needs to know what the expected response from the server looks like
and how to place that response back into the user's browser document.
AjaxFramework.js
// callback function that handles any state changes of our request to the server
function handleResponse() {
if(http.readyState == 1){
// request loading
document.getElementById("status").innerHTML
= "requesting...";
}
else if(http.readyState == 4) {
// request complete
if(http.status == 200) {
// OK returned
var response = http.responseText;
// Add more advanced parsing here if desired
document.getElementById("responseArea").innerHTML
= response;
}
else
{
document.getElementById("status").innerHTML
= "error: " + http.statusText;
}
}
}
The first thing the handleResponse function does is check the
current state of the request object. If the object is loading (1), then
the user is alerted to this, or if the request is complete (4) then we
handle the response. This example just puts the response text (use
responseXML for an XML response from a server) into our document's
responseArea.
Send a query to the server
Now that we have setup the request object structure, as well as the
state handling function, the next step is to create a function that our
webpage will be calling for each outgoing request. This function could
either accept information via an input parameter, or retrieve user
input by querying the document.
Once the user input is received, we create a GET request to a
URL. It is important to note that due to security concerns the request
can only be made to a server that is hosting the webpage. The domain
name must be exactly the same as the request URL, if there is a
preceding www. to the domain name. As usual, however, there are some
fairly straightforward work arounds for getting external data for your
Ajax requests. Several options will be discussed.
This example demonstrates using a REST input (parameters
passed via the URL), but other remote query and command options are
also possible. Furthermore, the open command supports passing a
username and password to the server for accessing protected services.
AjaxFramework.js
// function for filling out and sending a request - called by the actual webpage
function sendRequest() {
var query = document.getElementById("queryInput").value;
var queryURL = "http://localhost.com/service.php?q=" + query;
http.open('GET', queryURL);
http.onreadystatechange = handleResponse;
http.send(null);
return true;
}
We have now completed the necessary parts of our Javascript code to
handle creating, sending, and receiving an asynchronous request through
a client's browser.
Server handling of the request
The client makes a request to some service or page that is served on
the same domain as the original webpage. This service for this example
is expecting a value passed via the URL in the GET parameters. The
response can be well formed XML, or simple text that will be parsed by
the client's browser as discussed above in the handleResponse()
function.
service.php
<?php
$query = $_GET['q'];
$response = some_service_handling($query);
echo $response;
?>
This server page just passes the query onto another php function and
then echoes the response. Since our Ajax request from the browser has
made a GET request, this operates like any normal opening a page in a
browser. However, instead of the page showing up in a window, it is
handled by the client's handleReponse() function.
Using a remote service
As we mentioned earlier, security does not allow the Ajax,
specifically XMLHttpRequest, to call another domain in the GET URL. The
way around this is provide a locally served wrapper to the remote
service. We can parse and pass on each of the incoming parameters.
Also, many hosting services don't allow a URL to be opened via the
fopen() command, so this example uses curl to make a request to a
server. The subsequent response is read by the local server and then
returned to the calling Ajax function.
remote_service.php
<?php
$remote_params = "";
foreach($_GET as $key=>$value)
{
$$key = $value;
if($value != '')
$remote_params .= "&".$key."=".$value;
}
$remote_url = "http://remotehost.com/remoteservice.php?";
function get_content($url)
{
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HEADER, 0);
ob_start();
curl_exec ($ch);
curl_close ($ch);
$string = ob_get_contents();
ob_end_clean();
return $string;
}
$content = get_content ($remote_url.$remote_params);
echo $content;
?>
This example makes no checks on the incoming request. The query and
parameters are passed directly onto the remote service. In a real
application, it would be responsible to do some basic parameter
checking before passing on the request to someone else's hosting
service.
That said, it is still a means by which to provide asynchronous
services in your own website. You should also be aware that making
these remote calls may have longer response times. While this situation
is an excellent reason why an asynchronous interface provides a better
user experience, users may be left wondering if their request was just
lost. Therefore, you should, when appropriate, let the user know that
the request is pending in some way.
Furthermore, it would be possible to setup a timeout timer for
each request that would call abort() on the request object if the
request took too long.
Supporting non-Javascript functionality
This framework will generally work for any modern, Javascript
capable browser. However, not all users are using Javascript capable
browsers, and other users may have disabled Javascript. Therefore, it
is advised that your site support a non-Javascript version of your
interface. At the very least, alert the user that they will not be able
to use all of the functionality of your web application or page.
To provide a non-Javascript interface only when necessary, your
page should use the <noscript> tags paired with any
<script> sections.
Using the Framework
The Javascript framework is logical backend functionality of an Ajax
enabled website. In order to use Ajax, the page must be properly
constructed and typically web developers also wan the page to look
nice. For both of these requirements, we will use XHMTL and CSS
respectively.
Example query and response
Lets illustrate the Ajax framework with an example. Our service
could return a name and phone number of a contact from our webserver.
The query parameter, q, could be some search term, and the response
would be the contact's name, and phone number. Testing such a service
is easy:
http://localhost.com/service.php?q=Jones
We will then expect a response like:
Edward Jones, 800-555-1212
Our handleResponse functionality need to be expanded to split the response with the comma (or multiple commas for more data).
AjaxFramework.js (handleResponse)
var data = response.split(',');
// more advanced parsing
document.getElementById("contact_name").innerHTML
= data[0];
document.getElementById("contact_number").innerHTML
= data[1];
This example response illustrates how easy Ajax is to begin to use.
There is no need for complex XML parsing and handling. Any simple
response can be used to dynamically update web content. We must be
careful, however, as we have forced the response to return the
information in a specific order and format.
A more robust application should use XML to provide multiple
contact data. The response handler could then iterate through the
elements of the contact entry without having to predetermine the order
of the response. In our example, if we switched the contact name and
contact number order the application would behave incorrectly.
In this case, we would instead get the responseXML and parse the XML document tree similar to the DOM of the browser document.
AjaxFramework.js
var response = http.responseXML;
var contact_name =
response.getElementsByTagName('name').item(0);
var contact_number =
response.getElementsByTagName('number').item(0);
However, XML is not necessary, and may be daunting when first
starting to use Ajax, or integrate it into already existing web
services. Therefore, we will continue our example using the simple text
response. Since the XML handling is encapsulated in the
handleResponse() function, it is possible to later change to using XML
without modifying the rest of our framework.
Example page
To use the Ajax searching, we will need to provide an XHTML user
interface for the query input, and the service response. The first
thing we need to do is include our Javascript framework code in our
page:
<html>
<head>
<script type="text/javascript" src="AjaxFramework.js" charset="utf-8"></script>
</head>
Next we create the query input and "Send" button. Note the use of
the ambiguous anchor link, #, in the href tag. We use an href link to
allow standard style formatting of the "Send" button to match the rest
of the sites hyperlinks. By using the local anchor, but with no actual
anchor, the hyperlink won't cause a page refresh since the browser
thinks it is just scrolling down the current page. Another option would
have been to use a generic div and provide a unique formatting for Ajax
link as compared to actual hyperlinks.
<body>
<input type="text" size="30" id="queryInput" value="" />
<a href='#' onClick="sendRequest();">Send</a>
<div id="status"> </div><br/>
<div id="contact_name"> </div>
<div id="contact_number"> </div>
</body>
</html>
When the "Send" link is pressed, the queryInput text input is sent
as a query to our name lookup service. The user is free to continue to
use the web browser. When the response is sent from the server, the
retrieved name and number are placed in the contact_name and
contact_number divs.
A more advanced version of this application could add in-line
searching of the contact name as the user types, similar to
autocomplete.
Summary
Ajax is quickly transforming websites from repositories of data into
dynamic and useful web applications. This article demonstrated how easy
it is to get started with Ajax and add it to your own site. Some
examples you can use it for include form checking while the user is
entering information, site/document search, database row updating, or
editing web content in place.
For more advanced applications you may want to look at several
available and supported Ajax toolsets that provide a ready framework
and lots of other functionality. Prototype (see resources) is used in
Ruby on Rails for its Javascript Ajax functionality, and Sajax is an
Ajax toolset for PHP code.
Resources
Ajax technology
Ajax applications
Ajax toolsets
Ajax Framework
The following files are the summation of the framework code
developed in the article above. It can serve as a skeleton for building
your own Ajax applications. Place these files in your
/Library/WebServer/Documents directory on your Mac, and turn on
"Personal Web Sharing" in the "Sharing Preference Pane".
AjaxFramework.js
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function handleResponse() {
if(http.readyState == 1){
// request loading
document.getElementById("status").innerHTML
= "requesting...";
}
else if(http.readyState == 4) {
// request complete
if(http.status == 200) {
// OK returned
var response = http.responseText;
document.getElementById("status").innerHTML
= "loaded";
document.getElementById("responseArea").innerHTML
= response;
}
else
{
document.getElementById("status").innerHTML
= "error: " + http.statusText;
}
}
}
function sendRequest() {
var query = document.getElementById("queryInput").value;
var queryURL = "service.php?q=" + query;
http.open('get', queryURL);
http.onreadystatechange = handleResponse;
http.send(null);
return true;
}
AjaxDemo.html
<html>
<head>
<script type="text/javascript" src="AjaxFramework.js"></script>
</head>
<body>
<noscript>
Your browser does not support Javascript. Please upgrade your browser
or enable Javascript to use this site.
</noscript>
<input type="text" size="30" id="queryInput" value="" />
<a href='#' onClick="sendRequest();">Send</a>
<div id="status"> </div><br/>
<textarea rows="20" cols="70" id="responseArea" value="" ></textarea>
</body>
</html>
service.php
<?php
echo $_GET["q"];
?>
Andrew Turner is a Systems Development Engineer with Realtime Technologies, Inc. (www.simcreator.com)
and has built robotic airships, automated his house, designed
spacecraft, and in general looks for any excuse to hack together cool
technology. You can read more about his projects at www.highearthorbit.com.