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. Pingback: Digital Sandwich

  2. Pingback: Bien batido y revuelto » PEAR AJAX: un tutorial

  3. Sky

    Hello
    I have installed pear on the server.
    Then i have installed HTML_AJAX.
    How do i call ajax in my .php pages ?

  4. Joshua Eichorn Post author

    The AJAX calls come from the Javascript side to your php backend logic, im not quite sure what your asking. Check out the examples (in the pear doc dir) to get a better idea of how the basic setup works.

  5. Jeremy Moseley

    I am having trouble getting the example to work. The HTML_AJAX-0.2.1 is installed, but when I attempt to load up the example, the string count is not displayed and entering a string is not possible. The error seems to stem from the initial The error I receive is: object doesn’t support this property or method. Any help would be appreciated. I would love to get this working!

  6. Jeremy Moseley

    On reading post 7 I realized the html was stripped. In Internet Explorer I viewed the javascript error message which pointed to line 31 which is the onload method.

  7. Joshua Eichorn Post author

    I guess its a problem with the install, everything looks fine on my test copy. Do you have a URL i can view the error at. Also if you want quicker turn around on the debugging feel free to email me (josh@bluga.net) and i’ll my instant messenger info.

  8. Kazuyuki Ohgushi

    Jeremy,

    The same problem would occur on me. I installed HTML_AJAX-0.2.1 on PHP5.0.4.

  9. Joshua Eichorn Post author

    Ok the problem with the sample code and PHP5 is case. Right now HTML_AJAX uses the case your code is written in when exporting in php5. But it always uses lowercase in php4 since the upper case version isn’t available.

    I have a todo item for adding a compatability mode that also lowercases functions in php4. But for now if you need to be compatible between php 4 and 5, you’ll need to pass an array of method to export to registerClass.

    -josh

  10. Joshua Eichorn Post author

    Kazuyhuki:

    If you don’t install things using pear you need to set the location of the javascript libraries.

    $server->clientJsLocation = “path/to/jslibs”;

  11. Ivo Jansch

    Hi Joshua,

    the jpspan site is still down since the wiki broke down. But I was wondering, is HTML_AJAX supposed to be the successor to JPSpan? Or are they really 2 different projects? There doesn’t seem to be a lot of activity on jpspan, but there is on html_ajax. So it’s probably better to go with html_ajax?

  12. Todd

    This looks great. I’m anxious to start working with it, however, I’m trying to use HTML_AJAX version 0.3.0 without pear and am having trouble figuring out what I need to change to get it to work.

    Which files need to be edited? for example there are a number of includes for files in HTML/AJAX however I don’t have an HTML directory. I’ve made a test directory…
    /docRoot/test/AJAX.php
    /docRoot/test/AJAX/
    /docRoot/test/examples/
    /docRoot/test/js/

    given only this and the standard files within the supplied directories how would I make the examples work?

  13. Joshua Eichorn Post author

    Todd:
    Well first thing first, the easiest thing to do is to use HTML_AJAX with pear. At some point i’ll start building tarballs that are meant to be used without the pear installer but im not there yet process wise.

    That being said if you extract HTML_AJAX and then rename the root directory to HTML and put it in your include_path things should work.

    so in your case the test directory becomes HTML and everything should work.

  14. Todd

    I’ll definately look into PEAR. At the moment that seems like a larger learning process and I think I’m just a simple error away from getting HTML_AJAX to work.

    Following your advice I’ve renamed “test” to “HTML” However I stil get the same errors:

    http://localhost/HTML/examples/queue_usage.php
    yeilds — ReferenceError – Can’t find variable: livesearch

    I’ve also created a /docRoot/HTML/helloWorld with the above code to the same end. It seems to me that the “helloWorld” and “examples” dirs should be at the same level as “HTML” given that “server.php” tries to load “HTML/AJAX/Server.php” unfortunately that returns the same ReferenceError

    Thanks for your help.

  15. Todd

    I’m sorry, even setting “error_reporting(2047)” I cannot find a php error. I’ll keep looking.

  16. Todd

    Of course you’re correct. My local server just returns a blank page. I’m not sure why because I haven’t altered that file.

  17. Todd

    Briliant!!

    Tailing /var/log/httpd/error_log helped me debug the process. Ultimately in place of your “HTML” directory includes I placed a full path to the directory. I had to do it for all the files, and I missed a few the first time I tried. Fantastic work though. I’m going to try and embed it into the work I’m doing. I’ll let you know when I’m done so you can see YOUR results.

    Thanks again.

  18. Logan

    I see on my verison and on your live example that when I hit “How Random String” that the red loading box appears, but it dies there… just sits… However, Kazuyuki Ohgushi’s link does work… just curious what was different…

  19. Logan

    Ya this si the error I can see…
    Notice: Could find an init method for class: livesearch in /usr/share/pear/HTML/AJAX/Server.php on line 493

  20. Kevin Hutchinson

    You are the man! Wow! Blimey! This absolutely rocks! What I really love is that you used JSON to move data structures between PHP and JavaScript so I can move real data around, not just chunks of HTML. When I’ve finished the AJAX version of my site, I’ll be sure to offer you a free account to say thank you.

  21. Laubi

    your helloworld example didn’t work on my server until I changed the function names:
    addstring to addString
    stringcount to stringCount
    ..

  22. Joshua Eichorn Post author

    Laubi:
    This is caused by the fact that php5 supports case in function and class names and php4 doesn’t.

    If you want portability you can register the names manually instead of automatically.

    $this->registerClass($hello,’HelloWorld’,array(‘addString’,’randomString’,’stringCount’));
    This will give you the results you saw in both php4 and php5. You could also just register all lowercase to produce portable results, but if your goign to specify methods you might as well use case since it makes for nicer javascript.

  23. Marcus Bointon

    I’ve got a bunch of miscellaneous global functions that I want to expose to Ajax. I’ve built a wrapper class that uses __call to call them as if they were class methods, and it works very nicely. However, I’m guessing that you use introspection to get method names, which you can’t get when they’re hidden behind a __call construct, so HTML_Ajax will be unable to construct a stub. How might I work around that?

  24. Joshua Eichorn Post author

    Marcus:
    Look at my post above, you can specify the methods to export, when you register the class allowing you to register virtual functions.

  25. Newbie

    Tried it. The examples are working fine.

    But, I have a problem.

    I tried out the example “review” inside the example directory. I played around a bit with it. Tried to modify it by instantiating another class from inside the newReview function. But it doesn’t work. What might be the problem? 🙁

  26. Joshua Eichorn Post author

    I’m not really sure what you’re trying to do. On the PHP side its just normal PHP code, one thing that might be causing you problems is that your code is expected to work under E_ALL error handling by default.

    The best thing to do is create a quick test script that runs your PHP class outside of the AJAX context.

    If its a problem exporting a class to the AJAX side there are a couple of things to check. First check your server file and make sure its being exported correctly. Then check the generated stub server.php?stub=classname for example, you can check the case etc here, and then make sure its being included into the page your trying to use it.

    If you have have some code you want to show to make things more clear feel free to send a message to the mailing list: http://lists.bluga.net/mailman/listinfo/html_ajax-devel

  27. Ed

    I’m having some problems getting this to work. PHP 5.0.4, HTML_AJAX 0.3.3. tried on both linux and windows (server side). client side was tried on windows only.

    tried both firefox 1.5 and IE 6 (I think. Help|about just says side-by-side mode for version).

    The js console from firefox shows the following error on pageload:
    remoteHW.stringcount is not a function
    when i click on the approriate buttons i get:
    remoteHW.randomstring is not a function
    remoteHW.addstring is not a function

    I’m no expert on js, so i’m not sure why it’s not a function. calling the auto_server.php with the same args as used in the index.php results in a very impressive js file where I do see that function.

    any ideas?

  28. Joshua Eichorn Post author

    Ed:
    Sorry about that the problem is that php4 doesn’t support case and php5 does. The example above was created to run in php4 and doesn’t take the needed steps to make it work in php5. You can fix this problem by set the class and method names when registering the class on the server.

    So you have 2 options to make things work, change the javascript code to use case in all the method calls, (take a look at auto_server.php?stub=helloworld you’ll get an idea of what i mean), or register the methods all lower case.

    You can do this when you register the class change:
    $this->registerClass($hello);
    to:
    $this->registerClass($hello,’helloworld’,array(‘addstring’,’randomstring’,’stringcount’));

  29. Ed

    Aha! That did the trick. And I see the answer was given in #14. doh.

    Now it’s time to play around and see what I can figure out.

    Thanks, and good work Joshua

  30. Joshua Eichorn Post author

    Jim, im not sure what you mean file names shouldn’t matter. Just download the included code to see what i named things.

  31. Riccardo Tacconi

    The big problem with HTML_AJAX is that there is not a real API docs. I fell clueless. I am just able to use submitForm and replace function 🙁

  32. Joshua Eichorn Post author

    Riccaro:
    Yeah API doc wise we are hurting, but
    Have a look at the examples directory, there is an example of every method and every use case in there.

  33. Jochen Schneider

    Joshua, nice job so far. But i’m running in a problem right away testing a lil bit. I’m trying to use “autocomplete” in a form. I want to type some letters and get the result not in a div-container, but as a hidden textfield, so i can read the result when i press the submit button.
    Am i totally wrong?! Or could you hint me a bit?
    Thx a lot in advance!
    Jochen

  34. cenil

    Hi,
    Can anyone help me how to pass a variable that is get from ‘prompt()’ javascript function to php. I tried looking at the forum and mailing archive but I couldn’t find anything.

    I’m trying to insert a new record on a table. It’s working but I can retrieve the data straight away.
    e.g:
    If I do an INSERT, Then the next thing is SELECT statement. It won’t give my anything.
    However when the script finished, and I do a SELECT statement again. It will give me the result.

    Thanks in advance.

  35. Joshua Eichorn Post author

    Cenil: im really not sure what your trying to do, but you can pass the variable from prompt just like any other javascript variable, you make some sort of AJAX call.

    Ask on the HTML_AJAX mailing list if you have any specific code you want me to look at.

  36. Jon

    I’m looking at this and wondering, “why?”

    Is there a problem that HTML_AJAX is trying to solve? For some reason, I feel like it’s violating the MVC model of programming *and* doing something that’s typically considered a no-no … code writing code (php writing javascript functions).

    I typically use a prototype/json/php combination with a single php file that acts as the ‘ajax server’. I use various get variables and a switch statement to decide which classes to include and execute.

    Is this one of those “there’s more than one way to do it” approaches or am I missing the point?