Experiment: Refresher function

DOM scripting/AJAX function

As mentioned in my last article, I’m going to introduce you to some code that will simplify the use of basic Ajax-style functionality. I have a small collection of code snippets that allow you to do several things, but for now I’m going to concentrate on just one of them: loading data from a file on the server to a specific part of a web page without refreshing the whole page.

The name I thought of for this little function is Refresher. Other functions I’ve come up with using similar techniques are called Toggler, Sender, Swapper and Submitter. Snappy, eh? The functions and supporting code are all available to download from the experiments area on my website. These functions are all written in PHP, but they are simple enough to be converted to ASP or something else quite easily.

So, onto a bit of background. What we want to do is click a link which will send a request to a website, passing some additional parameters if required, then load the resulting content into a specified portion of the page. I could have got a whole lot more complex, using XML, forms and authentication, but this fitted the bill for my requirements at the time and I expect it will do much of what I need it to do for a long time.

So the bits of information we need are: the page we want to request, the parameters we want to send (if any), the resulting portion of the page to receive the result, and for good measure an optional timeout value. The timeout is the number of milliseconds the script should wait before executing. I’ll show you why I use timeout later on.

As you may know I’m a big believer (now I’ve discovered it) of unobtrusive JavaScript, which features heavily in Stuart Langridges book DHTML Utopia. The crux of all that is we don’t want horrible chunks of JavaScript appearing in our nice clean HTML code. Just in the way we separate presentational information (the CSS) from content (the HTML) we no longer do messy things like this:

<a href="javascript:alert('Get with it, man! Sheesh!');">Click me</a>

Instead we use the power of the DOM to target specific elements and assign actions to them for specific events. For this function I assign a "click" event to any element which is set as a "refresher" link, then send the parameters needed to perform the function using the elements ID. Sound complicated? It is, but I’ll try to explain it the best I can.

Creating the page

Firstly we need to create the web page. Something like this will do fine. Notice I’ve added a DIV to the page with the text "Current time:" and a link with the text "Click me to update the time". Further explanation should not be necessary for that.

Next we need to give the the DIV an id attribute which will uniquely identify it in the page. IDs must contain only the characters a-z (upper or lower case, but you need to to stick to the same capitalisation scheme throughout the document as this makes it much easier to read later on), 0-9, "-", "_" and ".". In this case I’m calling my DIV "showTheTime". Some browsers have problems with the underscore in id attributes, so I stick with alphanumeric characters, the period and the dash. Later on you’ll see why some special characters in id attributes are crucial to the working of the Refresher function.

And that’s it. Seriously, that’s pretty much all the HTML there needs to be for this to work. So we can start to add the other layers – CSS and JavaScript. You can see here that I’ve styled the page a bit with CSS to make it look pretty, and added a target for the link (which is the page we’re on).

Making the page all Refreshed

Next we include the Refresher function file in the head of the document. The code is simple:

<head>...

<? include "refresher.php"; ?>

...</head>

This presumes that the Refresher function file is in the same folder as the page you’re running. If not, just change the path to the Refresher file. Unfortunately this plasters the whole JavaScript code block into the page, not ideal. It would be better to have is as a separate file, but for easy of use I’ve made the Refresher function a single-file include. You can easily split up the two parts (PHP and JavaScript) yourself. It’s important to put the code in the head of the document so the JavaScript will run correctly.

The Refresher file itself is actually a mixture of PHP and JavaScript code, both of which are used in the creation and execution of the Refresher function. To invoke the function you need to make sure the link you want to activate the Refreshment process has a class of "refresher", like this:

<a href="" class="refresher">Click me to update the time</a>

Then we need to create a special id attribute for this link which can be used to pass the right parameters to the Refresher function. This is done using the PHP "refresherID" function:

<a href="" class="refresher" id="<? print refresherID('showTheTime','../loadtime.php','showtime=true',1000); ?>">Click me to update the time</a>

This is where Refresher really kicks in. There are four parameters passed to the refresherID function:

‘showTheTime’ is the name of the target elements (remember we called our DIV this a little while ago?)

‘../loadtime.php’ is the page we wish to call

‘showtime=true’ are the additional parameters to be sent to the processing page. These will be sent using the querystring (GET method) so they should be encoded

‘1000’ is the number of milliseconds before the function should execute

In line with our unobtrusive JavaScript mantra, we need to make sure that these parameters are not plastered all over our nice clean HTML code, so the PHP refresherID function encodes them and produces and ID for the element a bit like this:

refresher.-74-61-73-6b.-74-61-73-6b.-69-64-34.1000

Have a look at the source code of the final demonstration page to see how it looks for our example.

How the script works

The Refresher script is actually a series of functions that do several things. Here they are in a nutshell (or an unordered list, for the pedantics among you):

  • Sets up listeners to "listen" to every link that has class="refresher"
  • When one of those links is clicked, start the Refreshment process
  • The Refreshment process decodes the ID of the link clicked and creates the call to run the XmlHttpRequest function after the specified timeout interval
  • The XmlHttpRequest process sends the request and receives the resulting HTML
  • The HTML is then pasted back into the page inside the specified element

Running the whole thing

So, as you can see, nothing more needs to be done to get the whole caboodle ticking. As can be seen in the the demonstration page the function works with minimal HTML and just one PHP include file.

So the only thing remaining is to give you the script to download. And here it is, in Zip format. The usual GPL licence applies.

Leave a Reply