There and Back Again

AJAX Hello World with HTML_AJAX

This is a continuation of my AJAX Hello World series, in my earlier posts I covered sajax and JPSpan. In this article i’ll cover how to get a basic AJAX appliction up and running with HTML_AJAX. If you haven’t figured it out yet im one of the author’s of HTML_AJAX. The application in question is the same simple app as the other examples, it has an input box for adding random strings and an button to add a random one to a div.

When your using HTML_AJAX you have more choices then with either JPSpan or sajax. But to keeps things simple were going to use a setup similar to how we used JPSpan, an external server page that generates a JavaScript proxy which is included by our html page that does the actual action. HTML_AJAX could also be used sajax style with the proxy and server code generated inline, but I don’t recommend this usage since it remove your ability to cache the generated JavaScript.

Installing HTML_AJAX

This is nice and simple its simply:
pear install HTML_AJAX-alpha
If you don’t have pear setup on your server just follow the installation instructions in the PEAR Manual.

Setting up the Server Component

An HTML_AJAX server page is generally very simple, it creates an HTML_AJAX_Server instance, registers all the classes you want exported and handles incoming requests. The incoming requests can be three different types:

  • Client library request: query string includes ?client=all (can also be each of the seperate component parts)
  • Generated stub requests: query strings includes ?stub=classname (all keyword can also be used)
  • AJAX Requests: query string includes ?c=classname&m=methodname

Client and Stub requests can be combined into the same one, but remember there is a tradeoff when doing that. You’ll have less roundtrips to the server but generated stubs are more likely to change so they can hurt your cacheability. You also want to be careful about using stub=all since the stub for 10 different classes can be quite large. The next release will also allow for combining multiple classes in a stub request by seperating them with a comma like so: stub=test,test2. Finally a note on class names, in php4 they will be lower case since thats what PHP returns, if you would like to have case or need to guarantee php4/5 compatability you’ll want to use some optional paramaters to registerClass, the first is the name to register the class in JavaScript as, the second is an array of methods to export.
A basic server is shown below.

<?php

session_start();

require_once 'HTML/AJAX/Server.php';
require_once 'HelloWorld.class.php';

$server = new HTML_AJAX_Server();

$hello = new HelloWorld();
$server->registerClass($hello);

$server->handleRequest();

?>

A server like this works fine for small scale projects, but it might not be a good choice for something larger since you could be creating 20 class instances just to serve a request on one of them. Any custom setup also has to be done for each class. HTML_AJAX provides a way to manage this by extending the server class and adding an init method for each class. A server that does this for the same HelloWorld class is shown below.

<?php

session_start();

require_once 'HTML/AJAX/Server.php';

class AutoServer extends HTML_AJAX_Server {
        // this flag must be set for your init methods to be used
        var $initMethods = true;

        // init method for my hello world class
        function initHelloWorld() {
                require_once 'HelloWorld.class.php';
                $hello = new HelloWorld();
                $this->registerClass($hello);
        }

}

$server = new AutoServer();
$server->handleRequest();

?>

PHP Application Code

In the server examples above you’ll notice were including a Hello World class. This hasn’t changed from the JPSpan example. The only thing of note is that makes heavy use of session, many AJAX apps will share this same heavy use, so make sure your server setups can handle that.

<?php

// our hello world class
class HelloWorld {

        function HelloWorld() {
                if (!isset($_SESSION['strings'])) {
                        $_SESSION['strings'] = array('Hello','World','Hello World');
                }
        }

        function addString($string) {
                $_SESSION['strings'][] = $string;
                return $this->stringCount();
        }

        function randomString() {
                $index = rand(0,count($_SESSION['strings'])-1);
                return $_SESSION['strings'][$index];
        }

        function stringCount() {
                return count($_SESSION['strings']);
        }
}

?>

The HTML that ties it all together

To finish up our app we need to create the HTML that ties it all together. This is going to have two main parts, the main JavaScript logic, callback function for our async requests and a fake form. The call the form fake, because there is no form tags, were just powering everything off onclick event handlers on buttons. At some point in the future HTML_AJAX will support taking a normal form and magically turning it into an AJAX one but for now that thought is just in my head.

The page starts with normal HTML boiler plate and an include of our client library and the stub hello world class. They are done all in a single class since that makes sense for this example, if I had 10 classes it wouldn’t.

Next we build the callback hash, it has a method for each method in PHP, they will be called from the results from an async AJAX call. In this example each call back is really simple it either updates an element using innerHTML or appends to one. You could also use a normal JavaScript class instead of a hash, but thats only useful if you need multiple instances.

The next step is to create an instance of our helloworld class and create a helper function. When we create an instance of our proxy class we pass in our callback, if we didn’t the instance would work in a sync manner, which can be useful, but in this case would make for a choppy ui. The helper function do_addString isn’t anything exciting, it just clears out the textbox after we’ve submited its current value.

Finally we have the html body of the page, it contains our buttons with onclick event handlers that call remote functions. It also contains our output divs.

Trying out the sample

If you got this far you’ll want to try out the Hello World app were building. If you compare it against the JPSpan or sajax version you won’t notice many differences. The only visual one that should show up is loading notice in the top right corner. Since providing user feedback is such an important part of making a usable AJAX application HTML_AJAX includes this basic loading symbol out of the box. If you just want to customize its looks you just need to create an element with the id of HTML_AJAX_LOADING. Its shown by setting its display style to block, and hidden by setting display to none everything else is left up to you so make sure to take care of any positioning and setting its display to none so its hidden by default. If you want to do somthing more complex you can override HTML_AJAX.onOpen and HTML_AJAX.onLoad check out the current methods to see hows its done.

Finally you might notice some JavaScript errors if you try to make a lot of quick requests, like JPSpan HTML_AJAX only provides for one concurrent request at a time. This will change in the future giving you a number of different options but for now you can either keep those from happening at the application level, or just add a error handling function to HTML_AJAX.onError and ignore the call in progress ones.

You can also download the project and try it out on your own server, its available as a tar.gz or a zip.

Where to go from here

Now that you’ve had a look at HTML_AJAX you might be wondering how to learn more about it. For the moment your options are pretty limited. You can check out the examples dir (in the docs dir in pear or online) or you can ask questions on this post. You might also find the source to be useful, for now the newest version lives on my svn server.

Feed back is appreciated as I’ll use that to decide what features to add to HTML_AJAX and what to fully document next, feel free to post comments or trackbacks even if you have a lot to say.

Update:
This example won’t work correctly in PHP5 since the methods will be exported with CASE, take a look at the generated JavaScript if you don’t understand what i mean (auto_server.php?clalss=helloworld). See Comment #40 for your options to fix things.

103 thoughts on “AJAX Hello World with HTML_AJAX

  1. Pingback: PEAR Tutorials | PHP kitchen

  2. James

    Hi there,
    In my web page I have 2 different sections of the page that use AJAX to load information. The trouble i’m having is to work out how to have more than one loading message (‘HTML_AJAX_LOADING’) in the page. The reason I want this is to have the loading message next to the part that is loading so it doesn;t pop up at the wrong part of the screen. I’ve done many a web search and poked around but can';t work out how to do it – is there a way round this you’d advise me to follow?
    thanks

  3. Joshua Eichorn Post author

    James:
    You have a couple different options, but in every case it amounts to creating custom Open/Load functions. The second parameter to each of the global methods (default: http://svn.bluga.net/HTML_AJAX/trunk/js/Loading.js) should be a Request object and you could use that for custom loading messages.

    But if you want loading at the spot of the call i think i would create custom methods for handling the message on the proxy object (or if your not using a proxy on the Request object)

    proxy.dispatcher.options['Open'] = function() { logic to show message here }
    proxy.dispatcher.options['Load'] = function() { logic to hide here }