YA Perl Advent Calendar 2005-12-09

First we had SOAP and of course there was Bleach, but before we can get to COMET we have have to see how AJAX plays out. CGI::Ajax (a.k.a Perljax) is a simple framework for producing AJAX enabled form applications.

While the Perljax documentation can be a little intimidating, once you get through it to implementation it's clear the module works as advertised. You simply

  1. create a Perljax object with a callback for a subroutine to be invoked by the client
  2. call the renderer with your favorite flavor of CGI object and a reference to the subroutine from your favorite templating system that will return the contents of the page as a string
And you're off and running. CGI::Ajax handles the server-side request processing logic and creates the necessary client-side scripts. Of course you can make it more complicated as need be: call a seperate (external) URI instead of $self, process multiple inputs and outputs, etc. In particular, if you'd prefer to not let Perljax auto-inject the JavaScript into your content you can retrieve the magic bits by calling the show_javascript method. Finally, there are even live demos of the sample scripts included with the distribution on the CGI::Ajax website, please be gentle.

P.S. Takenote that the input and output references for the form field events refer to the element id and not the name, this may not be clear from a cursory glance at the documentation.


use CGI::Ajax;
use CGI::Minimal;

my $query = new CGI::Minimal;
my $AJAX = new CGI::Ajax( jsMethod=> \&perlMethod);

print $AJAX->build_html($query, \&createContent);

sub perlMethod{
  $_ = shift;
  $_ .= ' lol' if rand() > .9;
  return uc;

sub createContent{
  undef $/;
  return <DATA>;
This is our simple web page, you could use your favorite templating system
as well, anything that returns a string of HTML.
<input id="IN1" type="text" size="12" onKeyUp="jsMethod(['IN1'], ['OUT1'] );">
<div id="OUT1" style="color:white; background-color:black">
AJAX results show up here, input is AOL echoed.