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.

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.

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.

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



        HTML_AJAX Hello World
        

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.

var hwCallback = {
                randomstring: function(result) {
                        document.getElementById('canvas').innerHTML += '

'+result+'

'; }, stringcount: function(result) { document.getElementById('count').innerHTML = result; }, addstring: function(result) { document.getElementById('count').innerHTML = result; } }

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.

        var remoteHW = new helloworld(hwCallback);

        function do_addString() {
                remoteHW.addstring(document.getElementById('string').value);
                document.getElementById('string').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.



        
        
Number of Random Strings:
Add new String:

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. Joshua Eichorn Post author

    Jon:
    There are a lot of different ways to do this, and HTML_AJAX supports all of them.

    So HTML_AJAX_Server handles the PHP side, and you can either use generated stubs for easier JS programming or use a different API, HTML_AJAX.call etc for calling to the server without te stubs.

  2. Frank

    What and/or where do files get installed – pear install HTML_AJAX-alpha

  3. Frank

    Found it usr/lib/php/HTML/AJAX/ on OS X
    What web servers can this run on, other than apache?

  4. Joshua Eichorn Post author

    Frank: it should work on pretty much any web server, the only caveat being that it does use some variables in $_SERVER and im not sure if every server sets them. But I think those can all be worked around by setting the server url by hand.

  5. A'Quessir

    Hi. Don’t you know, where can i find free eBooks(or even articles) on AJAX&PHP?

  6. Chinaski

    I’ve installed the HTML_AJAX package and setup your tutorial script on my site, but I cannot get it to run. I’m getting a javascript error on line 22 of index.php (helloworld is not defined)

    var remoteHW = new helloworld(hwCallback);

    All I’ve done is untar the scripts and pointed my browser at them.

    I’m running php 4.4.2

    Any ideas?

    http://test.bourbonhours.com/HTML_AJAX-HelloWorld/

  7. Joshua Eichorn Post author

    IC: I’m not sure what you mean, if you have a specific error please email the HTML_AJAX mailling list and one of us will get things worked out for you

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

  9. Pingback: BAOHX

  10. Elky

    Hi all!

    Just yesterday AJAX caught my attention. Im writing text-based games
    in PHP in my spare-time using static java-script to produce the output and always considered that techtnique too complicated.

    So reading my first pages about PEAR and AJAX, this sounds very promissing to me.

    The example HelloWorld I got to run on PHP5 changing to caps as well.
    For now I would like tzo follow this track as I just finished a course in java-2 including some webdevelopping and enjoy to find classes here again. I will try to make a little game using ajax, hoping I can make it support some action ๐Ÿ˜‰

    Greetings to all, keep on the nice work! Ralf

  11. Showunmi J

    Hello Joshua, I’m am new to HTML_AJAX, I downloaded your sample code and I even changed register line as you indicated above. However, the script doesn’t respond to the button clicks talkless of sending the input.

    You help would be greatly appreciated.

  12. mrhavercamp

    Hi all,

    I was just looking at the example formSubmit in the HTML_AJAX bundled docs and am a little confused; in order to execute a submit with formSubmit you need to post from form.php to server.php so I might as well just use an html form and handle the post server-side in a regular manner. Am I missing the point of formSubmit completely? I’m really amp-ed to use HTML_AJAX but the lack of documentation is killing me. If anyone could point me in the direction of a HTML_AJAX form submit tutorial or even a snippet of code it’d be much appreciated.

  13. wang suya

    I tryed Webpage http://wiki.bluga.net/HTML_AJAX/start? example

    A basic server is shown below, in the file server.php:

    handleRequest();
    ?>

    page.html:

    I’m the target

    HTML_AJAX.replace(‘target’,’output.php’);

    output.php:

    “. strftime(“%H:%M:%S”) .””);
    ?>

    but it only show onetime time and it was not our local time(Japan) it was 11:17:02. Then I push the button but the time did not change. I tryed to change the output.php’s output contents but it was not reflected still 11:17:02. Do I have to download the all the js file in my server how can I download them? or do I have to setup our server’s proxy? I am run PHP5.
    Thank you very much.

  14. wang suya

    I installed HTML_AJAX by PEAR into my server, but I looked at there is no .js file.

  15. wang suya

    Joshua: I installed Pear in /usr/local/lib/php. because my php installed here and core pear was installed hear, too. You mean I shoud install pear in /usr/share/pear/ then the js file will automatically installed in /usr/share/pear/data/HTML_AJAX/js/HTML_AJAX.js. Therefore I should move core pear from /usr/local/lib/php to /usr/share/pear but it will seperate from php is it ok?

  16. wang suya

    Joshua: I download the HTML_AJAX from http://htmlajax.org/HTML_AJAX/Manual?#toc5

    then I still keep my PEAR in /usr/local/lib/php. I mv js to /usr/local/lib/php/HTML/js. I installed HTML_AJAX from command line use pear install HTML_AJAX-beta. I follow the manual add one line $server->jsClientLocation = ‘/usr/local/lib/php/HTML/js’; in the
    Webpage http://wiki.bluga.net/HTML_AJAX/start? example, but it does not work, too. I push the button, but the time still not change. Could tell me why?

  17. wang suya

    Joshusa: I installed Firefox then try this example. It correctly worked. But Use IE to run this example it did not work. I do not know how to investiage javascript errors in IE. Do you know why IE does not work?

  18. wang suya

    Joshua: I tryed HTML_AJAX’s exmaples in IE6, some worked and others did not work. for example Form.php in IE6 it did not work but in Firefox it worked. Why?

  19. wang suya

    Joshua: I downloaded HTML_AJAX-0.5.1 then move it to server:/usr/local/lib/php/ and unfreeze it, tar it, but it could not be tared. Why?

  20. wang suya

    Joshua: I try to use HTML_AJAX.replace as bellow:

    function settd(){
    if(document.f.a1.checked){
    HTML_AJAX.replace(‘target’,’output.php’);
    }
    }

    I’m the target

    but it does not work. I try to realize that when I check the checkbox then one php file be excuted. In php file DB access and dom access are excuted. How can I use HTML_AJAX to realize it?

  21. wang suya

    It seem that html file could not replay to maillist. The checkbox
    click is simplized like ” input type = “checkbox” name = “a1” onClick = “settd()”

  22. Prem

    Hi,

    I get a request time out error of 20000ms. How can I change this number to something like 40,000ms?

    Thanks
    Prem

  23. wang suya

    Joshua: 4 weeks ago, you told me to use http://htmlajax.org/HTML_AJAX/release-0.5.1?
    but I download it then refreeze it and tar it but it did not success. When I tar it
    there are the message like :” XXXX are not directory”.
    I throwed this question to maillist you told me but no response.

  24. Joshua Eichorn Post author

    Wang: Did you try using the pear installer, there might be some issues with the tarball but since it was made with the pear insaller there shouldn’t be any issues with it extracting it.

  25. Pingback: creativecrap bloground » Blog Archive » AJAX ๅˆ้ซ”้ฉ—

  26. Sandie

    joshua: im new to php as well HTML_AJAX
    in auto_server.php we r doing…
    $server = new AutoServer();
    but how this is instantiating HTML_AJAX_Server() object.
    this might be a Class concept,can u explain how
    $server = new AutoServer() is doing work for HTML_AJAX_Server() class

  27. Pingback: polysyncronism.com » Blog Archive » Joshua Eichorns Blog ยป Blog Archive ยป AJAX Hello World with HTML_AJAX

  28. Chris

    Hi Joshua,

    I tried all I could to run your Hello World on my system, but I face something I never quite seen before in HTML (especially when I see none whatsoever)
    a Syntax Error (damn, that remind me of the good old GW-BASIC…)

    same thing with my typed version as well as your own version when copied/pasted… I don’t know where to look… I don’t know if it’s related, but after all maybe… my index.php is named helloworld.html (is there an issue with naming it .html instead of .php??)

    the syntax error is on line 2!!!

    excerpt: (I only suppose, eh…)

    Line 1:
    Line 2:
    Line 3: HTML AJAX Hello World
    Line 4:
    etc…

    any advice/help ??

    thanks ๐Ÿ™‚

    Chris

  29. Joshua Eichorn Post author

    If your using ie6 then the provided line # means nothing. If you use ie7 or firefox you’ll get a more reasonable error message. Using .html instead of .php for the helloworld file shouldn’t matter since there is no php in that file.

  30. Leo

    Do I need copy also the directory HTML/AJAX to the same directory I put the webpage?

    This is the first time I using PEAR. Therefore, I don’t know how it works.

    require_once โ€˜HTML/AJAX/Server.phpโ€™;
    Will PHP automatically find the place of the request page in PEAR (in this case, the page is Sever.php), or we have to indicate where it is?

    When I try the example, It doesn’t work unless I copy the directory HTML_AJAX to same place will example.

  31. Leo

    Hi! I found the solution ๐Ÿ˜€ Sorry about my stupid question ๐Ÿ˜€

    To make PEAR work on Windows, you simple need to add the PEAR installation dir (e.g. c:\php\pear) to the include_path directive in your php.ini.

    Note: There are some classes (like Schedule/At.php), that do not work on Windows, because they use *nix specific commands.

  32. pfarthing6

    the working example is broken. Javascript error: remoteHW has no properties. Using FF-2.0.0.6

    Also this seems like way too much work and code to just do a simple xmlHTTP request to get some data off of a server and place it somewhere in a document and just shouldn’t even need any session vars to do it.

  33. Joshua Eichorn Post author

    pfarthing6:

    The sessions are there because you want to store data in the session. AJAX doesn’t get rid of the need of sessions.

    Things were broken because of PHP5/PHP4 case differences

  34. Oren

    Is it possible to set php class members without accessing a method.
    For example: changing the variable $d from the javascript remoteClass.d=4

    <?
    class a{

    var $d;

    function s(){}

    }

  35. Joshua Eichorn Post author

    Oren:

    HTML_AJAX doesn’t support this and you really wouldn’t want to do that anyway since making an http request to set a single variable would be horrible slow and inefficient