TweetFollow Us on Twitter

Adding Ajax to a Website

Volume Number: 22 (2006)
Issue Number: 1
Column Tag: Programming

Adding Ajax to a Website

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.

 
AAPL
$102.50
Apple Inc.
+0.25
MSFT
$45.43
Microsoft Corpora
+0.55
GOOG
$571.60
Google Inc.
+2.40

MacTech Search:
Community Search:

Software Updates via MacUpdate

Path Finder 6.5.5 - Powerful, award-winn...
Path Finder is a file browser that combines the familiar Finder interface with the powerful utilities and innovative features. Just a small selection of the Path Finder 6 feature set: Dual pane... Read more
QuarkXPress 10.2.1 - Desktop publishing...
With QuarkXPress, you can communicate in all the ways you need to -- and always look professional -- in print and digital media, all in a single tool. Features include: Easy to Use -- QuarkXPress is... Read more
Skype 6.19.0.450 - Voice-over-internet p...
Skype allows you to talk to friends, family and co-workers across the Internet without the inconvenience of long distance telephone charges. Using peer-to-peer data transmission technology, Skype... Read more
VueScan 9.4.41 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
Cloud 3.0.0 - File sharing from your men...
Cloud is simple file sharing for the Mac. Drag a file from your Mac to the CloudApp icon in the menubar and we take care of the rest. A link to the file will automatically be copied to your clipboard... Read more
LibreOffice 4.3.1.2 - Free Open Source o...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
SlingPlayer Plugin 3.3.20.505 - Browser...
SlingPlayer is the screen interface software that works hand-in-hand with the hardware inside the Slingbox to make your TV viewing experience just like that at home. It features an array of... Read more
Get Lyrical 3.8 - Auto-magically adds ly...
Get Lyrical auto-magically add lyrics to songs in iTunes. You can choose either a selection of tracks, or the current track. Or turn on "Active Tagging" to get lyrics for songs as you play them.... Read more
Viber 4.2.2 - Send messages and make cal...
Viber lets you send free messages and make free calls to other Viber users, on any device and network, in any country! Viber syncs your contacts, messages and call history with your mobile device,... Read more
Cocktail 7.6 - General maintenance and o...
Cocktail is a general purpose utility for OS X that lets you clean, repair and optimize your Mac. It is a powerful digital toolset that helps hundreds of thousands of Mac users around the world get... Read more

Latest Forum Discussions

See All

Rhonna Designs Magic (Photography)
Rhonna Designs Magic 1.0 Device: iOS Universal Category: Photography Price: $1.99, Version: 1.0 (iTunes) Description: Want to sprinkle *magic* on your photos? With RD Magic, you can add colors, filters, light leaks, bokeh, edges,... | Read more »
This Week at 148Apps: August 25-29, 2014
Shiny Happy App Reviews   | Read more »
Qube Kingdom – Tips, Tricks, Strategies,...
Qube Kingdom is a tower defense game from DeNA. You rally your troops – magicians, archers, knights, barbarians, and others – and fight against an evil menace looking to dominate your kingdom of tiny squares. Planning a war isn’t easy, so here are a... | Read more »
Qube Kingdom Review
Qube Kingdom Review By Nadia Oxford on August 29th, 2014 Our Rating: :: KIND OF A SQUARE KINGDOMUniversal App - Designed for iPhone and iPad Qube Kingdom has cute visuals, but it’s a pretty basic tower defense game at heart.   | Read more »
Fire in the Hole Review
Fire in the Hole Review By Rob Thomas on August 29th, 2014 Our Rating: :: WALK THE PLANKUniversal App - Designed for iPhone and iPad Seafoam’s Fire in the Hole looks like a bright, 8-bit throwback, but there’s not enough booty to... | Read more »
Alien Creeps TD is Now Available Worldwi...
Alien Creeps TD is Now Available Worldwide Posted by Ellis Spice on August 29th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Dodo Master Review
Dodo Master Review By Jordan Minor on August 29th, 2014 Our Rating: :: NEST EGGiPad Only App - Designed for the iPad Dodo Master is tough but fair, and that’s what makes it a joy to play.   | Read more »
Motorsport Manager Review
Motorsport Manager Review By Lee Hamlet on August 29th, 2014 Our Rating: :: MARVELOUS MANAGEMENTUniversal App - Designed for iPhone and iPad Despite its depth and sense of tactical freedom, Motorsport Manager is one of the most... | Read more »
Motorsport Manager – Beginner Tips, Tric...
The world of Motorsport management can be an unforgiving and merciless one, so to help with some of the stress that comes with running a successful race team, here are a few hints and tips to leave your opponents in the dust. | Read more »
CalPal Update Brings the App to 2.0, Add...
CalPal Update Brings the App to 2.0, Adds Lots of New Stuff Posted by Ellis Spice on August 29th, 2014 [ permalink ] | Read more »

Price Scanner via MacPrices.net

Are We Now In The Post-Post-PC Era?
A longtime and thoroughgoing laptop aficionado, I was more than a little dismayed by Steve Jobs’s declaration back in 2010 when he sprang the iPad on an unsuspecting world. that we’d entered a “post-... Read more
Apple now offering refurbished 21-inch 1.4GHz...
The Apple Store is now offering Apple Certified Refurbished 21″ 1.4GHz iMacs for $929 including free shipping plus Apple’s standard one-year warranty. Their price is $170 off the cost of new models,... Read more
Save $50 on the 2.5GHz Mac mini, on sale for...
B&H Photo has the 2.5GHz Mac mini on sale for $549.99 including free shipping. That’s $50 off MSRP, and B&H will also include a free copy of Parallels Desktop software. NY sales tax only. Read more
Save up to $300 on an iMac with Apple refurbi...
The Apple Store has Apple Certified Refurbished iMacs available for up to $300 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free. These are the best prices on... Read more
The Rise of Phablets
Carlisle & Gallagher Consulting Group, a businesses and technology consulting firm focused solely on the financial services industry, has released an infographic depicting the convergence of... Read more
Bad Driver Database App Allows Good Drivers t...
Bad Driver Database 1.4 by Facile Group is a new iOS and Android app that lets users instantly input and see how many times a careless, reckless or just plain stupid driver has been added to the... Read more
Eddy – Cloud Music Player for iPhone/iPad Fre...
Ukraine based CapableBits announces the release of Eddy, its tiny, but smart and powerful cloud music player for iPhone and iPad that allows users to stream or download music directly from cloud... Read more
A&D Medical Launches Its WellnessConnecte...
For consumers and the healthcare providers and loved ones who care for them, A&D Medical, a leader in connected health and biometric measurement devices and services, has launched its... Read more
Anand Lal Shimpi Retires From AnandTech
Anand Lal Shimpi, whose AnandTech Website is famous for its meticulously detailed and thoroughgoing reviews and analysis, is packing it in. Lal Shimpi, who founded the tech site at age 14 in 1997,... Read more
2.5GHz Mac mini, Apple refurbished, in stock...
The Apple Store has Apple Certified Refurbished 2.5GHz Mac minis available for $509, $90 off MSRP. Apple’s one-year warranty is included, and shipping is free. Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.