Tue 08 Mar 2005

How Does It Work?

Here's a CL-AJAX version of the ModernMethod tutorial for SAJAX, which does exactly the same thing in PHP (though with a bit less functionality on the server side, as far as I can tell). I've cribbed some of the text to make the similarity as similar as possible. Apologies to ModernMethod, and to my readers for the abysmal <pre> formatting.

  1. Include the library:
    (asdf:operate 'asdf:load-op :cl-ajax)
  2. Initialise it and tell it what functions you wish to export:
    ;; the function we will be exporting 
    ;; to JavaScript:
    (defexported multiply (x y) (* x y))
    ;; set the server running:
    (install-handler
    (http-listener-handler *listener*)
    (make-instance 'ajax-function-handler)
    *site-url* nil)
    (start-listening *listener*)
  3. Setup your HTML (including the JavaScript the library generates)
    <html>
    <head>
    <title>Test</title>
    <script>
    <!--
    here Araneida inserts the results of
    (build-preamble *site-url*)
    -->
    function set_math_result(result) {
    document.getElementById("z").value = result;
    }
    function do_the_math() {
    var x, y;
    x = document.getElementById("x").value;
    y = document.getElementById("y").value;
    // The Lisp function (multiply) has been
    // linked to a javascript function named
    // ajax_multiply() with defined args. call it.
    // Also specify if XML will be expected.
    ajax_multiply(x, y, set_math_result, false);
    }
    </script>
    </head>
    <body>
    <input type="text"
    name="x" id="x"
    value="2" size="3">
    *
    <input type="text"
    name="y" id="y"
    value="3" size="3">
    =
    <input type="text"
    name="z" id="z"
    value="" size="3">
    <input type="button" name="check"
    value="Calculate"
    onclick="do_the_math(); return false;">
    </body>
    </html>
Thanks to security features in most modern browsers this won't work if you just save it locally — I threw a quick static-file-handler into Araneida to serve the saved HTML, and it worked like a charm:
That's the raw XML response, the form from the original SAJAX example calling into CL-AJAX, and Vim showing the (frankly awful) generated code.

Posted at 2005-03-08 15:57:06 by RichardLink to How Does It Work?