Ajax: Asynchronous JavaScript and... uh....
What is Ajax?

It's not a language. It's not a development tool. It's not a library. It's a strategy. Ajax is often confused with DHTML, which is easily a far more complex set of concepts to learn. Ajax, on the larger scale, might be thought of as a strategy that encompasses the use of httpRequests (the same kind of request your browser makes to get HTML, CSS and JavaScript for a page that it's going to display) along with DHTML (Dynamic HTML: the use of JavaScript to get and set DOM properties) to make a page highly interactive without requiring a full page reload for every instance of data transmission.

The following diagram may help you understand the difference between full-page reloads and lightweight Ajax calls:

Ajax_vs_PageReloads.png
What are the Benefits?

In addition to just making your site look and feel slicker by changing small bits, Ajax also prevents requiring full-page reloads, which - especially in the case of heavy-load pages - can drastically improve the efficiency and usability of your web site. It allows you to only serve up the new information that you want without having to serve up the rest of the surrounding content that hasn't changed, and it improves the user experience by not jumping the page to the top again, leaving other changes that have been made on the page untouched, and allowing the user to better maintain their orientation on the current page after a change has been effected. In game scenarios, Ajax is also immensely useful in saving progress, points and other data states without requiring the game play to be put completely on hold in order to refresh the page. It also allows your page to ping for new data, making up-to-date news feeds and chat boxes possible where they otherwise would have required 'refresh' or 'submit' buttons.

`
So how do I do it?

It typically boils down to a single function. There are two ways these functions can work. They can be separately threaded functions that allow the rest of the script on the page to continue and that simply perform a callback function that you pass along with it once the httpRequest is complete, or they can be functions that halt the rest of the page while the and directly return any output that is generated from the httpRequest. The examples we'll look at will involve the latter (a direct call and output return), but many libraries like Dojo and jQuery make use of the former type, which allows you to pass in a function to call after completion without stopping whatever else is going on on the page.

The Function

Without further ado, let's take at the ajax() function that I'm going to introduce here. To view the actual code behind this function, you can check out the ajax.js script that this page uses. I will make the assumption that you have copied this function to your own JavaScript library and have made it available to the page that you will use it in. Here is the function call, as a basic skeletal example:

var x = ajax(method,file,parameters);

The "method" argument requires to either "get" or "post". If you're calling a relatively short set of query parameters in your URL (the stuff that comes after the '?'), then you can use "get" without any trouble. For larger data submissions, you'll want to use "post". The disadvantage to "post" is that if you later use a tool like Firebug to view the call that was made, the page that opens won't explicitly show the parameters in the address bar. However this is usually unproblematic, and in many cases, the use of "get" or "post" will have little or no impact on your application.

The "file" argument is a string containing the location/name of the file that you will be submitting this request to. This file will often be a PHP or other dynamically-generated file, because that way any parameters that you submit can be considered before generating the custom output that will be returned to you. This will make more sense in examples soon to come.

Finally, the "parameters" argument is a string containing everything that should come after the "?" in a url, or the fields that would have been submitted in a posted form. Typically you will build this string up in JavaScript based on user input and/or the current state of the page. I will show some examples of that further below once I cover the basics of making the call and retrieving the output.

Here is a more fleshed-out example of it's use. First, note the contents of this text file, which is located in the same directory as this tutorial page.

var tableCode = ajax("get","sample1.txt",""); document.getElementById('output1').innerHTML = tableCode;

It was that easy! The Ajax call simply grabbed the output from sample1.txt (which is static output representing an HTML table) and dropped it right into the output1 div as instructed. Note that I included an third parameter (the empty "") because there were no variables to pass to the sample1.txt page... but that could have actually contained some variable values if my script required it.

A Dynamic Example using PHP

Having just mentioned it, let's look at a PHP example so you can see the usefulness more clearly. Since you can't see the source of sample2.php, here's what it contains:

<? // grabs $n and outputs its square $n = $_GET['n']; $x = $n*$n; print $x; ?>

This page will output the square of any number 'n' that you pass to it. You can see this as a normal page load by visiting sample2.php?n=2. It simply outputs '4', because 'n=2' was passed after the '?' mark. (This is a PHP/CGI concept, and I won't go into it in much more detail. If you know how to make it useful, by all means make use of it!) In any case, since we're able to pass a URL that way, it would be handy if we get that result using Ajax. Here's a modified JavaScript:

var tableCode = ajax("get","sample2.php","n=2"); document.getElementById('output2').innerHTML = tableCode;

What's the next logical step? Why to collect the number from the user, of course!...

try { var n = document.getElementById('nInput').value; var tableCode = ajax("get","sample2.php","n="+n); document.getElementById('output3').innerHTML = tableCode; } catch(er) { alert(er); }

Enter a number:

Conclusion: The Impact on Our Work

While the PHP example was relatively simplistic, and the square of the number entered could have just been calculated in JavaScript, I hope the usefulness of this call is becoming somewhat clear. Rather than calling up the easily-computable square of a number, what if you were to pass in a string of keywords to a script that searched for matching places and output them in the form of JSON that you could loop through and place on a map? Suddenly you have a rich, useful application using an easy-to-implement function, some basic knowledge of PHP, and a very set of basic JavaScript array looping concepts.


Recommended next: Play with the Google Maps API!