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:

<?php

$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.

<?php

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

$server = new HTML_AJAX_Server();

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

$server->handleRequest();

?>

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:

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 HTML_AJAX.call 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.

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.


22 Responses to “Adding AJAX to a website step by step”

  1. 1

    Joshua Eichorn’s Blog: Adding AJAX to a website step by step…

  2. 2

    [...] In his latest post, HTML_AJAX package developer Joshua Eichorn shares his methods for adding Ajax to an example website (with HTML_AJAX’s help, of course), and he shows it step-by-step. [...]

  3. 3

    [...] In his latest post, HTML_AJAX package developer Joshua Eichorn shares his methods for adding Ajax to an example website (with HTML_AJAX’s help, of course), and he shows it step-by-step. 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. 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. The Webthumb mentioned there is a pet project of his, allowing for the generation of thumbnails taken directly of websites (more on that here). He uses an updated to this application as his illustration. He demonstrates the remoting functionality, his use of a class named RequestStatus for finding the status of the Ajax connection, exporting this in the PHP (easy thanks to HTML_AJAX), and make the actual calls to the backend with the newly exported function. August 8th, 2006 [...]

  4. 4

    [...] There and Back Again The weblog of Joshua Eichorn, AJAX, PHP and Open Source « Adding AJAX to a website step by step [...]

  5. 5

    [Ajax] Adding Ajax to a Website, Step By Step…

    Joshua Eichorn has a two-part set of articles in which he shows how he added Ajax to his web application WebThumb in order to improve usability. He writes:

    Webthumb is a small project of mine that takes a snapshot of a website and gives you thumbn…

  6. 6

    [...] Back with the second part of his postings on adding Ajax to a website, Joshua Eichorn has this new item on his blog today (picking up from this previous post) – a look at polling the server for the latest data with the HTML_AJAX PEAR package. I have a lot more change’s i’d like to make to webthumb so the last article (Adding AJAX to a website step by step) is now the start of the series. In this article will be taking front page of webthumb and making it live. The the stats and recent thumbnails will update in real time, making for a nice slick presentation. He first focuses on getting real-time information back with the help of Ajax. In his case, it’s grabbing the latest thumbnails created by the application, fetched by periodic polling back from a timed script performing an Ajax request. He moves on to the code, showing how to export the PHP class for the updater, a sample result for the request and the code for the actual server the Ajax request will be made to. Then, it’s back to the client side of things with the Javascript needed to make the call back to the server, parse the response, and update the page with the latest information. There’s also a little aside that talks about how the HTML_AJAX package delivers it’s Javascript libraries and how this can be used to grab and push out the moo.fx library along with the other scripts to create a a fade in and out of the updates made to the page to make them more apparent to the user. August 10th, 2006 [...]

  7. 7

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

  8. 8

    [...] There and Back Again » Blog Archive » Adding AJAX to a website step by step Adding AJAX to a website step by step [...]

  9. 9

    [...] http://blog.joshuaeichorn.com/archives/2006/08/08/adding-ajax-to-a-website-step-by-step/ [...]

  10. 10

    [...] Making AJAX calls to RequestStatus | read all the topic in details… [...]

  11. 11

    [...] I have a lot more change’s i’d like to make to webthumb so the last article (Adding AJAX to a website step by step) is now the start of the series. In this article will be taking front page of webthumb and making it live. The the stats and recent thumbnails will update in real time, making for a nice slick presentation. [...]

  12. 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. 13

    Sorry, forget the Btw. part, found it on http://blog.joshuaeichorn.com/archives/2006/08/21/webthumb-rendering-engine-released/

    The question about inProgress is still valid.

  14. 14

    statusCheckCallback is called by HTML_AJAX with the results of an AJAX request.

    HTML_AJAX.call(‘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.

  15. 15

    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.

  16. 16

    Greg:
    You got it.

  17. 17

    [...] Adding AJAX to a website step by step [...]

  18. 18

    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.

  19. 19

    Ajax mit PHP…

    Einzelne Bereiche von Webseiten dynamisch zu aktualisieren ist eine tolle Sache. Heutzutage fällt für diesen Zweck sofort das Buzzword Ajax. Wobei es völlig egal ist ob man die Daten nun in XML (AjaX), JSON oder sonst wie verpackt. Auch ich möchte …

  20. 20

    I was looking for some ajax stuff like this one. thanks

  21. 21

    [...] Links zu diesem Thema: SeoFox, Adding AJAX to a website step by step (II) Dr. Webs Nachschlagewerk für AJAX-, DHTML- und [...]

  22. 22

    [...] nutzen. Dieses Paket wird entwickelt und unterstützt von Elizabeth Smith, David Coallier, Joshua Eichhorn (er stellt auch eine gute Dokumentation bereit), Laurent Yaish und Arpat Ray.Insgesamt finde ich [...]


Leave a Reply

This circle expands additional navigation