Ajax Web Hosting with Lunarpages

Unless you've been under a rock for the last 12 months, you've undoubtedly heard of Ajax. Forgive the cliché, but instead of cleaning your kitchen sink, Ajax cleans up the traditional web experience and brings out shiny usability in web pages. Ajax stands for Asynchronous Javascript and XML, but most the prominent letter is the J. There has been a lot of effort to add synchronicity (making the order of things matter) and avoid the use of XML (by returning Javascript instead), so Ajax can be thought of as more of an approach.

Ajax is a wonderful new tool to improve usability of sites. Although developers must be careful about what is possible, the added functionality is worth it. Many established internet companies are using Ajax. Yahoo uses it for their homepage and the user interaction. It is also used in their Yahoo Music system for rating songs. Google's very popular Gmail email client is a Ajax web application, as is Google maps. This article is actually being written using an Ajax application. The GoogleDocs part of the Google website is a fully-functional word processor. It allows users to edit files with all of the functionality of Microsoft Word, or other word processors. It's defining improvement over traditional desktop based processors, is it's portability. Because your file exists on Google's servers, you can access it from anywhere you have computer access. It also allows collaboration on documents and the ability to publish your work to a website, for anyone can view it.

The traditional web site approach is to display pages and reload the page when you click on links. The Ajax approach is to NOT reload the entire page when links are clicked, but instead only reload the relevant data. This is accomplished by using Javascript to mimic the action of going to a page and getting data. For instance, let's say a page has a list of products. There are a few ways to show more detailed information about this product. When the user clicks on the product, the "normal" way to find out information about the product is to go to a new page. The "Ajaxy" way is to have Javascript request (go to) the page with the extra info about this product and then have Javascript get the data and display it on the page the user is already on.  While both ways are functional, the Ajaxy way is faster. It also is significantly "smaller" than the normal way because it can save bandwidth.

While an incredibly powerful approach to web development: Ajax does come with a few risks. The most obvious one is that the pages generally do not work if a user does not enable Javascript. Most statistics show that approximately 10% of Internet users do not have Javascript enabled. Because of this, it is important to either develop pages that still work whether Javascript is enabled or not. Graceful degradation is very important if are making sales or need to make sure that everyone (and every browser) can use your site. A more serious risk involves "hackers" exploitation. According to Wikipedia :

Cross site scripting (XSS) is a type of computer security exploit where information from one context, where it is not trusted, can be inserted into another context, where it is. From the trusted context, an attack can be launched. http://en.wikipedia.org/wiki/XSS

This can happen if a knowledgeable user tries to fake the type of requests that your Javascript requests would make. For instance, a hacker might try to display a different product or a different category. More likely, the hacker will try to use the parameters of your pages to execute their own commands. Some Free (as in beer) ways to combat this is to send POST requests instead of GET requests, and to make sure that your Javascript sends extra information that ensures the request has come from a valid resource (in this case, the page on your website). It is also essential to make sure that any user input fields, no matter how mundane, are stripped of Javascript code and HTML tags. Problems can arise when this is allowed, so it is important to take great care when developing.

Now for the nitty gritty. While still in it's infancy, Ajax has given new life to the Javascript programming language and many new libraries to ease the use of development have risen up to meet the challenge.. There are many popular ones, including dojo, Rico, the Yahoo User Interface library (YUI), the Google Web Toolkit (GWT). While all of these toolkits offer Ajax support, and have great pros and cons, the most popular one is Prototype. According to an Ajaxian.com poll, 43% of those polled use the framework.

Our first example will be a simple photobook. The first step is going to http://prototype.conio.net/ and downloading the Javascript file. When this is done, make sure to have your page include the file.

<SCRIPT language="JavaScript" src="prototype.js" type="text/JavaScript"></SCRIPT>

The basic HTML for our example follows:

<button onclick='showPhoto("apple");'>Show Apple</button>
<button onclick='showPhoto("orange");'>Show Orange</button>
<button onclick='showPhoto("banana");'>Show Banana</button>

<div id='photo'>
    <img src="apple.jpg" />
</div>

The main point of this code is to have an HTML element with a unique ID, in this case 'photo'. The buttons have onClick event handlers set so that when each button is clicked it will call the appropriate function. Now for the Javascript:

<script type="text/JavaScript">

function showPhoto(fruit)
{
        params = 'fruit='+fruit;
        var myAjax = new Ajax.Updater( 'photo', 'photo.php', {parameters: params});
}
</script>

The Prototype library has a built-in class called Ajax, interestingly enough, and it has a very useful function called Updater. The Updater function takes the ID to be updated with new content, the page to send the content to (called the Request Handler), and parameters to pass along to our Request Handler. The parameters are in the JavaScript Object Notation (JSON) format. I use PHP in the majority of my development, so I use 'photo.php' as my Request Handler. Any web programming language can replace PHP in this respect as long as it accomplishes the main function. My photo.php takes the "fruit" parameter, tacks a '.jpg' onto the end, and print outs an image tag.

<?php
//Get Post
$fruit = $_POST['fruit'];
$image = $fruit.'.jpg';
print "<img src='$image'>";
?>

A full working example can be seen here. Obviously, this is a very simple example but the beauty of Ajax is that it scales upward very gracefully. A developer is able to keep most of the logic out of Javascript and into their main development language, while keeping the Javascript small and unobtrusive. Ajax is also useful for tracking users and sending request even when there is not result you would like to display. Javascript can continually send request back to the server to check how long a user has been logged in, for instance. It can also be used to parse user input for validation or it could be used to set cookies that need to be used in other portions of a site.

Another useful tool that exists in the Prototype library is the ability to update multiple fields at once. The "traditional" way to do this is to have your Request Handler script print XML from your request, and have Javascript parse and extract the necessary information. A more intuitive way, is to use return Javascript from your Request Handler.

For example, we use the following as our html code:

<input name='num' id='num' />  
<button onclick="calculate()">Calculate Number</button>
<div id='number_box'>
10
</div>

I then use the following javacript call to change the content of the number box:

<script type='text/JavaScript'>

function calculate()
{
params = 'number='+$F('num');
var myAjax = new Ajax.Request(
'number.php',
{
parameters: params,
evalScripts: true
}
);
}
</script>

The biggest difference in this call is that we use the Ajax.Request function instead of the Ajax.Updater function. This general purpose function allows the return of more structured information than the Update function. It also allows the Javascript that is returned to be executed. This is done by using the evalScripts parameter that is sent along with the request. This code also introduces the $F() function. What this function accomplishes is returning the value of a form element, without manually traversing the HTML page. The form input must have a unique ID, but the function works flawlessly.
The code below prints out an interesting addition to Javascript, the $ function. What this function does is either return the actual HTML element that it is looked for, or an array of elements if more than one is found.

My php Request Handler page simple updates the number box content on the page, AND it also changes the color of the content based on its sign.

The corresponding php code looks like this:

<?
$number = $_POST['number'];
header("Content-type: text/javascript");
if($number > 0)
{
        $new_number = $number * 1000;
        print "$('number_box').innerHTML = $new_number ;";
        print "$('number_box').style.color = 'silver';";
}
if($number < 0)
{
        $new_number = $number * -1000;
        print "$('number_box').innerHTML = $new_number ;";
        print "$('number_box').style.color = 'red'";
}
?>

The full code for this example can be seen here.

Definitions

AJAX stands for Asynchronous JavaScript And XML.
AJAX is not a new programming language, but a new way to use existing standards.
With AJAX you can create better, faster, and more user-friendly web applications.
AJAX is based on JavaScript and HTTP requests.
AJAX is a type of programming made popular in 2005 by Google (with Google Suggest).

AJAX Web Hosting with Lunarpages

5 things you can do with AJAX Web Hosting

Advantages of Using Ajax

Disadvantages of Using AJAX

Tested for safety by the Safe Shopping Network Host Critique Award WebHost Magazine Award Hosting Review Award Top 8 Web Hosting Award Listed on Dunn & Bradstreet