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
$96.13
Apple Inc.
+0.53
MSFT
$42.86
Microsoft Corpora
-0.30
GOOG
$566.07
Google Inc.
-5.53

MacTech Search:
Community Search:

Software Updates via MacUpdate

Data Rescue 3.2.4 - Recover lost data on...
Data Rescue is a robust and reliable hard-drive recovery solution for your Mac. Recover lost or deleted files, mount corrupted drives, and more -- Data Rescue offers complete relief from crippling... Read more
Adobe Lightroom 5.6 - Import, develop, a...
Adobe Lightroom software helps you bring out the best in your photographs, whether you're perfecting one image, searching for ten, processing hundreds, or organizing thousands. Create incredible... Read more
OneNote 15.2 - Free digital notebook fro...
OneNote is your very own digital notebook. With OneNote, you can capture that flash of genius, that moment of inspiration, or that list of errands that’s too important to forget. Whether you’re at... Read more
iStat Menus 4.22 - Monitor your system r...
iStat Menus lets you monitor your system right from the menubar. Included are 8 menu extras that let you monitor every aspect of your system. Some features: CPU -- Monitor cpu usage. 7 display... Read more
Ember 1.8 - Versatile digital scrapbook....
Ember (formerly LittleSnapper) is your digital scrapbook of things that inspire you: websites, photos, apps or other things. Just drag in images that you want to keep, organize them into relevant... Read more
OmniPlan 2.3.6 - Robust project manageme...
With OmniPlan, you can create logical, manageable project plans with Gantt charts, schedules, summaries, milestones, and critical paths. Break down the tasks needed to make your project a success,... Read more
Command-C 1.1.1 - Clipboard sharing tool...
Command-C is a revolutionary app which makes easy to share your clipboard between iOS and OS X using your local WiFi network, even if the app is not currently opened. Copy anything (text, pictures,... Read more
Knock 1.1.7 - Unlock your Mac by knockin...
Knock is a faster, safer way to sign in. You keep your iPhone with you all the time. Now you can use it as a password. You never have to open the app -- just knock on your phone twice, even when it's... Read more
Mellel 3.3.6 - Powerful word processor w...
Mellel is the leading word processor for OS X and has been widely considered the industry standard since its inception. Mellel focuses on writers and scholars for technical writing and multilingual... Read more
LibreOffice 4.3.0.4 - 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

Latest Forum Discussions

See All

Bio Inc. is $0.99 for the Weekend, Recei...
Bio Inc. is $0.99 for the Weekend, Receives Small Update Posted by Ellis Spice on August 1st, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Happy 7th Birthday Readdle! Thank You fo...
Happy 7th Birthday Readdle! | Read more »
Sharknado: The Video Game Review
Sharknado: The Video Game Review By Lee Hamlet on August 1st, 2014 Our Rating: :: SHARKNA-DON'TUniversal App - Designed for iPhone and iPad Sharknado: The Video Game brings the craziness of the movies to iOS, though it quickly... | Read more »
Clima (Weather)
Clima 1.0 Device: iOS iPhone Category: Weather Price: $.99, Version: 1.0 (iTunes) Description: Clima show you all weather information, just beautifully simple. A series of color bars can tell you at a glance exactly current... | Read more »
Sticky Soccer Review
Sticky Soccer Review By Andrew Fisher on August 1st, 2014 Our Rating: :: STICK THIS GAMEUniversal App - Designed for iPhone and iPad Sticky Soccer puts too much emphasis on the ‘sticky’ and not enough on the ‘Soccer’ or ‘Fun’.   | Read more »
Graphics-less Apocalyptic Adventure A Da...
Graphics-less Apocalyptic Adventure A Dark Room Goes Free for a Limited Time Posted by Rob Rich on August 1st, 2014 [ permalink ] | Read more »
Fraud Tycoon Review
Fraud Tycoon Review By Rob Thomas on August 1st, 2014 Our Rating: :: UNHEALTHY CREDITUniversal App - Designed for iPhone and iPad Fraud Tycoon is a half-baked, messy, promotional tie-in that does their sponsor no favors whatsoever... | Read more »
Guardians of the Galaxy: The Universal W...
Guardians of the Galaxy: The Universal Weapon is on Sale for the Weekend Posted by Rob Rich on August 1st, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Mister Beam Review
Mister Beam Review By Jordan Minor on August 1st, 2014 Our Rating: :: ILLUMINATINGUniversal App - Designed for iPhone and iPad Mister Beam’s puzzles are great. But its platforming? Not so much.   | Read more »
Hook Some More Fun With MapHook’s New Up...
Hook Some More Fun With MapHook’s New Update Posted by Jessica Fisher on August 1st, 2014 [ permalink ] iPhone App - Designed for the iPhone, compatible with the iPad | Read more »

Price Scanner via MacPrices.net

13-inch MacBook Airs on sale for $100 off MSR...
B&H Photo has the new 2014 13″ MacBook Airs on sale $100 off MSRP. Shipping is free, and B&H charges NY sales tax only. They also include free copies of Parallels Desktop and LoJack for... Read more
16GB iPad Air on sale for $399, save $100
Best Buy is offering the 16GB WiFi iPad Air for $399.99 on their online store for a limited time. Their price is $100 off MSRP. Choose free shipping or free store pickup (if available). Price is for... Read more
All Over For Tablets Or Just A Maturing, Evol...
CNN’s David Goldman weighs in on tablet sector doom and gloom, asking rhetorically: “Is this the beginning of the end for the tablet?” Answering that, he contends that hysteria and panic are... Read more
Letterspace 1.0.1 – New Free iOS Text Editor...
Bangkok, Thailand based independent developer Sittipon Simasanti has released Letterspace, a new text editor for iPhone, iPad, and iPod touch devices. Letterspace is a note taking app with an... Read more
Save up to $130 on an iPad mini with Apple re...
The Apple Store has Certified Refurbished 2nd generation iPad minis with Retina Displays available for up to $130 off the cost of new models, starting at $339. Apple’s one-year warranty is included... Read more
iPad Cannibalization Threat “Overblown”
Seeking Alpha’s Kevin Greenhalgh observes that while many commentators think Apple’s forthcoming 5.5-inch panel iPhone 6 will cannibalize iPad sales, in his estimation, these concerns are being... Read more
Primate Labs Releases July 2014 MacBook Pro P...
Primate Labs’ John Poole has posted Geekbench 3 results for most of the new MacBook Pro models that Apple released on Tuesday. Poole observes that overall performance improvements for the new MacBook... Read more
Apple Re-Releases Bugfixed MacBook Air EFI Fi...
Apple has posted a bugfixed version EFI Firmware Update 2.9 a for MacBook Air (Mid 2011) models. The update addresses an issue where systems may take longer to wake from sleep than expected, and... Read more
Save $50 on the 2.5GHz Mac mini, plus free sh...
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 $140 on an iPad Air with Apple ref...
Apple is offering Certified Refurbished iPad Airs for up to $140 off MSRP. Apple’s one-year warranty is included with each model, and shipping is free. Stock tends to come and go with some of these... Read more

Jobs Board

Position Opening at *Apple* - Apple (United...
**Job Summary** The Apple Store is a retail environment like no other - uniquely focused on delivering amazing customer experiences. As an Expert, you introduce people Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** At the Apple Store, you connect business professionals and entrepreneurs with the tools they need in order to put Apple solutions to work in their 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
Sr. Product Leader, *Apple* Store Apps - Ap...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
Sr Software Lead Engineer, *Apple* Online S...
Sr Software Lead Engineer, Apple Online Store Publishing Systems Keywords: Company: Apple Job Code: E3PCAK8MgYYkw Location (City or ZIP): Santa Clara Status: Full Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.