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.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.