Easy As Pie

This post is the second in a continuing series of DIY tutorials, which aims to make things as simple as possible.

Ajax. Some would say that it is simply an over-used buzzword, but I disagree. Ajax (formerly known as AJAX) is a fantastic way to enhance websites and improve user interactivity. However, like all things, it should be used in moderation, and has the potential to be used improperly (I'm looking at you, flash.)

But I don't want to get off-topic so early on. In this tutorial, you will:

  • Learn how to use Ajax in the simplest way I could think of
  • Create an addictive voting script
  • Create a simple shoutbox
  • Download source and create your own within minutes!

But first, I will explain a bit about what Ajax really is (and what it isn't) for those of you just starting out.

What Ajax Isn't

Ajax is not flashy JavaScript. Ajax is not a fancy form, radical menu or custom tool-tip. Ajax is definately not a styled popup.

What Ajax Is

Ajax, also known as XHR, is a technology used to send and receive requests for data to and from a server without having to refresh the whole page. That's really all there is to it.

Don't let that put you off though! You can still accomplish some really neat things using Ajax. The first 'neat thing' is a voting script. You click a button to vote, which will poll phazm.com's server and come back with an updated tally of how many votes there are -- without a single page refresh. Fascinating, am I right?

Let's Vote!

Alright, here's the little script I made. This took me about 12 minutes to write the script, 8 minutes to set up the database, and 2 minutes to come up with the idea. (For those of you keeping track at home, that's a total of 22 minutes!)

Note: Feel free to vote more than once to see the number rise.

Which one is the cutest?

And the winner is... Ajax!

This is obviously a very (very) simple example of what Ajax can do, but it's effective, nonetheless. There are significant advantages to using Ajax for this, rather than straight JavaScript. While I could emulate this in JavaScript, the votes would have to be saved on your machine via cookies or sessions and other votes wouldn't be counted, only your own.

So how did you do it?

Like this!

function getHTTPObject() {
 var xhr = false;
 if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
 } else if (window.ActiveXObject) {
  try {
   xhr = new ActiveXObject("Msxml2.XMLHTTP");
  } catch(e) {
   try {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
   } catch(e) {
    xhr = false;
   };
  };
 };
 return xhr;
};

function fillElementId(url,elementId) {
 if(!document.getElementById(elementId)) {
  return;
 };
 parameters = encodeURI(parameters);
 var xmlHttp = getHTTPObject();
 xmlHttp.onreadystatechange=function(){
  if(xmlHttp.readyState==4){
   if(xmlHttp.status==200){
    document.getElementById(elementId).innerHTML = xmlHttp.responseText;
    xmlHttp=null;
   } else {
    alert("Error: "+xmlHttp.statusText);
   };
  };
 };
 xmlHttp.open('POST',url,true);
 xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 xmlHttp.setRequestHeader("Content-Length", parameters.length);
 xmlHttp.setRequestHeader("Connection", "close");
 xmlHttp.send(parameters);
};

Let's break it down line by line:

getHTTPObject

function getHTTPObject() {

This is the function that actually loads the XmlHttpRequest

var xhr = false;

Simply pre-defining the variable.

if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();

Firefox, Safari, Opera and Netscape and IE7 all use window.XMLHttpRequest

} else if (window.ActiveXObject) {

window.ActiveXObject is used by IE6 and below.

xhr = new ActiveXObject("Msxml2.XMLHTTP");

Internet Explorer 6 uses Msxml2.XMLHTTP

xhr = new ActiveXObject("Microsoft.XMLHTTP");

IE 5 uses Microsoft.XMLHTTP

xhr = false;

If you get in here, it means your browser doesn't support XHR

return xhr;

This returns the value of 'xhr' to whatever called it.

fillElementId

function fillElementId(url,elementId) {

This is the function that tells the XHR what to do, and this is the function you can modify.

if(!document.getElementById(elementId)) {
return;

This will check if the id you gave it exists, and if it doesn't, it will break out of the function.

parameters = encodeURI(parameters);

This will encode the parameters passed to it, turning spaces (" ") into %20 and the like.

var xmlHttp = getHTTPObject();

As you can see, we have just defined xmlHttp as the function we looked at earlier. This simply sets xmlHttp to whatever is returned from the getHTTPObject function.

xmlHttp.onreadystatechange=function(){

This will fire off every time the readyState changes

if(xmlHttp.readyState==4){

readyState can be any of the following:

  • 0 = uninitialized
  • 1 = connection open
  • 2 = data sent
  • 3 = receiving data
  • 4 = transaction complete

if(xmlHttp.status==200){

status is the HTML status received, these are the most commonly received:

  • 200 = OK
  • 301 = Redirected
  • 400 = Bad Request
  • 401 = Unauthorized
  • 403 = Forbidden
  • 404 = Not Found
  • 408 = Request Timeout
  • 500 = Internal Server Error
  • 503 = Service Unavailable

document.getElementById(elementId).innerHTML = xmlHttp.responseText;

This simply replaces everything in the container with the ID we specified with whatever is in the variable xmlHttp.responseText

xmlHttp=null;

This removes the reference to the object

alert("Error: "+xmlHttp.statusText);

This will output what the server returns, such as "Not Found" or "Forbidden"

xmlHttp.open('POST',url,true);

This is where you open the request. You can use either GET or POST for the request. The "true" means asynchronous, so if you change it to false, it will wait for a response before doing anything else.

xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

This tells the script to expect a form

xmlHttp.setRequestHeader("Content-Length", parameters.length);

This declares the length of the parameters to the script

xmlHttp.setRequestHeader("Connection", "close");

If you want to have a persistent connection, you don't need this line, but I don't want a persistent connection open, so I close it.

xmlHttp.send(parameters);

This sends the request, which will begin to change the readyState, and thus start firing off the above code, and wait for the readyState to be 4.

Initiation

Then you have to initiate it somehow, which I am doing using an onclick event. You should probably add this event unobtrusively, but for examples sake I'm doing it inline.

<a id="link1" onclick="fillElementId('/landfill/CallMe.php','link1','link=1')" href="javascript:void(0)">I have 2 votes</a>
<a id="link2" onclick="fillElementId('/landfill/CallMe.php','link2','link=2')" href="javascript:void(0)">I haz 3</a>

So when you click on one of those links, it sends the three variables (url, elementId and parameters) that are in the onclick to the fillElement function.

The function calls the url, and replaces the content of the element with that id with whatever it gets from the url. Simple enough?

Here's another really simple example:

Phazm Shoutbox Mini (beta!)

  • dede said: tete
  • fucker said: you suck
  • hg said: dgdgdg
  • not bad said: not bad
  • xxx said: asdfasdfasdf
  • xxx said: sexsex
  • test said: test
  • Doron said: Test
  • test break said: breakkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
  • dsfg said: safddddddffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffuuuuuuuuuuuuuuuuuuuuucccccccccccccccccccccckkkkkkkkkkkkkkkkkkkkk

How did you do that, then?

Almost exactly the same as the voting script. The only thing that changed was the onclick (or onsubmit, in this case)

Now, it's calling a different php file, with two variables: name and msg - the PHP is doing the rest, as it should.

Ajax - A Dumb Waiter

Jeremy Keith said in last years Web Directions North (Links to 2008 page) that Ajax should be a "dumb waiter" - Not doing any of the heavy lifting, just sending and receiving data that is generated server-side. This way, you have less problems with browser imcompatibilities and such, and it makes the speed of your application depend on your server, not on the computer running the code.

So there you have it, your very own Ajax script -- Easy as Pie!

Download It

If you would like to download the JavaScript file, you may do so at this link. Feel free to use it any way you want to, you don't need to link back unless you wish to.

What's next?

I'm thinking an "Easy as Pie - Debugging CSS and JavaScript" next, but that might change depending on the comments I receive here. What would YOU like to see simplified?

  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • Ma.gnolia
  • Technorati
  • Fark
  • NewsVine
  • Slashdot
  • blogmarks