Adding AJAX to a website step by step

Update: The next article in this series is now complete.

Webthumb is a small project of mine that takes a snapshot of a website and gives you thumbnails in 4 different sizes. Currently the site is rather boring and has a couple of usability problems especially on the pickup page. Over the next couple of days I’ll be using various AJAX techniques to upgrade Webthumb, writing about the process as things happen.

When looking at a adding AJAX you have a couple decisions you’ll want to make up front. One is what tools your going to use. In the webthumb case thats pretty easy. Webthumb is a simple PHP app and doesn’t use a framework, so I need a nice general PHP/AJAX framework that is easy to use, HTML_AJAX fits that need. I may also need so animations or other effects, since im not planning on doing anything really fancy i’ll use the extremly small but powerful moo.fx. I’ll also keep scriptaculous in mind if I end up needing something fancier, but I think its overkill for this project.

After picking my tools I need to decide what my goals are. My main focus will be to improve usability, but I also want to use AJAX to make the site seem a bit flashier, so its a bit of a technology demo too.

Updating Thumbnail Pickup

The first page im targeting is the thumbnail pickup page. Thumbnail generation is an asyncronous process, you make a request which is added to a queue and the thumbnail processor walks the queue generating thumbnails updating the status when its done. The current way this is handle is by letting the user reload the page a bunch of times, but the speed of thumbnail generation isn’t consistent so if things run slow its easy to thing something is broken. I’ll be fixing this by using AJAX to poll the server on a 1 or 2 second interval, and use that information to make some sort of a progress bar.

HTML_AJAX and PHP remoting

HTML_AJAX supports a number of different ways to add AJAX to your pages, in this case I’ve chosen to use its PHP remoting supporting. This works registering a PHP class to be used by JavaScript, and then using a proxy object from JavaScript to make calls or making calls with the classname and methodname specified. Since im only going to be making a few calls im not going to be using a proxy object, if you want some examples on how that works checkout my Hello World with HTML_AJAX post.

The RequestStatus PHP class

The class i’ll be exporting too JavaScript is call RequestStatus it currently has a single method, getStatus. If you were using it in PHP a call would look something like:

$status = new RequestStatus();
$jobStatus = $status->getStatus($jobId);

// job is in queue
if ($jobStatus['status'] == 'queue') {
  echo 'Job is in Queue, there are '.$jobStatus['wait'].' jobs in front of it';
else if ($jobStatus['status'] == 'processing') {
  echo 'Job is being processed, it started at'.$jobStatus['start'];
else if ($jobStatus['status'] == 'complete') {
  echo 'Job is complete';

Exporting a PHP Class

The easiest way to make a PHP class available to JavaScript is too use the HTML_AJAX_Server class. If your using a framework you can either integrate this class into your front controller to handle AJAX dispatch or you can use the HTML_AJAX class directly and write your own equivalent of HTML_AJAX_Server to handle call dispatch. I run HTML_AJAX_Server inside of a file called ajax.php, an example of which is shown below. The only item of note is that im specify the methods on that class to export, doing this is always a good idea, and its the only way to keep method case in php4.

require_once 'lib/RequestStatus.class.php';
require_once 'HTML/AJAX/Server.php';

$server = new HTML_AJAX_Server();

$server->registerClass(new RequestStatus(),'RequestStatus',array('getStatus'));


At this point a good thing is test that the class has been registered correctly and isn’t thowing any PHP errors. To do this load the generated JavaScript stub up in your browser, ajax.php?stub=RequestStatus. For any class the result should look something like below:

// Client stub for the RequestStatus PHP Class
function RequestStatus(callback) {
	mode = 'sync';
	if (callback) { mode = 'async'; }
	this.className = 'RequestStatus';
	this.dispatcher = new HTML_AJAX_Dispatcher(this.className,mode,callback,'/webthumb/ajax.php?','JSON');
RequestStatus.prototype  = {
	Sync: function() { this.dispatcher.Sync(); }, 
	Async: function(callback) { this.dispatcher.Async(callback); },
	getStatus: function() { return this.dispatcher.doCall('getStatus',arguments); }

Making AJAX calls to RequestStatus

Now that the backend is setup its just a matter of making some AJAX calls on the thumbnail pickup page.

To do this we’ll create a new JavaScript function will be run by the pages onload handler. It will start a timer that makes a call to getStatus every 2 seconds, as long as another request isn’t currently being waited on. Will be using to make the requests.

To get the needed JavaScript libraries I specify a client parameter too ajax.php. Im grabbing all the default libraries and the optional alias library. Alias lets me type $(‘id) instead of document.getElementById.

My status code check code is pretty simple, if the status is complete is reload the page, and let the PHP code display the images. If not I display a new status message, either the items ahead of this thumbnail job in the queue, or the time that processing started on the thumbnail. I also added a simple animated loading gif. The status check JavaScript is below, followed by the HTML it updates.

HTML_AJAX.defaultServerUrl = 'ajax.php';
var inProgress = false;
var jobId = '< ?php echo $jobId; ?>';
var statusInterval;

function setupStatusCheck() {
        statusInterval = window.setInterval(statusCheck,2000);
function statusCheck() {
        if (inProgress) {

        inProgress = true;'RequestStatus','getStatus',statusCheckCallback,jobId);
function statusCheckCallback(result) {
        inProgress = false;

        if (result.status == 'complete') {
                window.location = '< ?php echo $_SERVER['PHP_SELF']; ?>?id='+jobId+'&reload=true';
        else if (result.status == 'processing') {
                $('statusMessage').innerHTML = 'Thumbnail generation started at '+result.start;
        else if (result.status == 'queue') {
                $('statusMessage').innerHTML = 'Your thumbnail is in the processing queue, there are '+result.wait+' items ahead of it';

Your thumbnail is in the processing queue, there are < ?php echo $waiting; ?> items ahead of it.

This page will automatically update when the thumbnail is complete.

There are a number of other enhancements we could make to this page. First it could use some CSS cleanups to look nicer. You could also skip the last reload by adding the images using JavaScript. And finally I could make a nicer way to show the 4 thumbnails. These enhancements and some some fun project on the front page will be covered in future articles.

Oh and these changes are live, so you can check them out by visting webthumb and putting in a url.

25 thoughts on “Adding AJAX to a website step by step”

  1. Pingback:

  2. Pingback: Ajaxian » Adding AJAX to a website step by step

  3. Pingback: Adding AJAX to a website step by step > Archives > Web 2.0 Stores

  4. Pingback: There and Back Again » Blog Archive » Adding AJAX to a Website step by step, Part II

  5. Pingback: Tucows Farm: The Tucows Developers' Hangout

  6. Pingback: Adding AJAX to a Website step by step, Part II > Archives > Web 2.0 Stores

  7. Yes, finally thank you, I have honestly been looking for a program similar to this, and I think this will work. Thanks!

  8. Pingback: Thomas Kahl » There and Back Again » Blog Archive » Adding AJAX to a website step by step

  9. Pingback: ♥.Sữa chua Media….. » Blog Archive » Adding AJAX to a website step by step

  10. Pingback: Adding AJAX to a website step by step » Dee’s-Planet! Blog

  11. Pingback: Adding AJAX to a website step by step, Part II » Dee’s-Planet! Blog

  12. Could you comment on the use of the global boolean javascript variable inProgress?
    I can only see, that once it is true, it will never be set to false again, except for a “manual” call of statusCheckCallback.
    On the other hand, I do not see, how it could ever become true, after leaving statusCheck.

    Btw., what do you use to make the snapshots, is this some kind of browser emulation?

  13. statusCheckCallback is called by HTML_AJAX with the results of an AJAX request.‘RequestStatus’,’getStatus’,statusCheckCallback,jobId);

    .call makes an async AJAX request to an exported method on a PHP class, the third parameter is the JavaScript function to call with the results. All parameters after that get passed to PHP.

  14. Thanks Joshua,
    I am not used to async requests yet. So .call() sends the request to the PHP script (speaking maybe a little oversimplified), then it may take a while for the server to answer, and statusCheckCallback() is called when the request is answered by the server. If that’s the case, then I understand. If not, perhaps you could give me another hint.

  15. Pingback: Fernando Meyer’s WebLog » Ajax links[]

  16. Hi
    I am working as a Website Designer. I want to learn AJAX. I know ASP,DotNet and little bit of Java Script. So will this help me in learning AJAX.

  17. Pingback: .: blogging augusto :.

  18. Pingback: Sebastian Bauer (IT-Blog) » Ajax mit PHP

  19. Pingback: HTML_AJAX aus dem PEAR-Framework mit JsMin zu schlankerem JavaScript Code optimieren | Location Bretagne Blog

  20. Pingback: Adding AJAX to a Website step by step, Part II - Ajaxian

  21. Pingback: 30 Ajax Tutorial | AJAX Rader - Best collection of AJAX Tutorials

Comments are closed.