CGI::Ajax(3pm)
π CGI::Ajax π
okay bestie, welcome to CGI::Ajax(3pm) β it lives in the User Contributed Perl Documentation, and it is literally the moment for doing async web stuff with Perl. Buckle up, this is part 1 and we're going deep. π¦
β¨ NAME β¨
CGI::Ajax β a perl-specific system for writing Asynchronous web applications. no cap, that's the whole vibe. π
πΈ SYNOPSIS πΈ
use strict;
use CGI; # or any other CGI:: form handler/decoder
use CGI::Ajax;
my $cgi = new CGI;
my $pjx = new CGI::Ajax( 'exported_func' => \&perl_func );
print $pjx->build_html( $cgi, \&Show_HTML);
sub perl_func {
my $input = shift;
# do something with $input
my $output = $input . " was the input!";
return( $output );
}
sub Show_HTML {
my $html = <<EOHTML;
<HTML>
<BODY>
Enter something:
<input type="text" name="val1" id="val1"
onkeyup="exported_func( ['val1'], ['resultdiv'] );">
<br>
<div id="resultdiv"></div>
</BODY>
</HTML>
EOHTML
return $html;
}
When you use CGI::Ajax within Applications that send their own header information, you can skip the header:
my $pjx = new CGI::Ajax(
'exported_func' => \&perl_func,
'skip_header' => 1,
);
$pjx->skip_header(1);
print $pjx->build_html( $cgi, \&Show_HTML);
There are several fully-functional examples in the 'scripts/' directory of the distribution. go look, they're adorable and they work. π
π DESCRIPTION π
CGI::Ajax is an object-oriented module that provides a unique mechanism for using perl code asynchronously from javascript-enhanced HTML pages. It unburdens you from having to write extensive javascript, except for associating an exported method with a document-defined event (such as onClick, onKeyUp, etc). CGI::Ajax also mixes well with HTML containing more complex javascript β no drama, it plays nice. π«Ά
CGI::Ajax supports methods that return single results or multiple results to the web page, and it supports returning values to multiple DIV elements on the HTML page. so many divs. so many results. it's giving versatility. β¨
Using CGI::Ajax, the URL for the HTTP GET/POST request is automatically generated based on HTML layout and events, and the page is then dynamically updated with the output from the perl function. Additionally, CGI::Ajax supports mapping URL's to a CGI::Ajax function name, so you can separate your code processing over multiple scripts. iconic behavior fr fr. π
Other than using the Class::Accessor module to generate CGI::Ajax' accessor methods, CGI::Ajax is completely self-contained β it does not require you to install a larger package or a full Content Management System, etc. no bloat, only vibes. π
We have added support for other CGI handler/decoder modules, like CGI::Simple or CGI::Minimal, but we can't test these since we run mod_perl2 only here. CGI::Ajax checks to see if a header() method is available to the CGI object, and then uses it. If method() isn't available, it creates it's own minimal header. π§
A primary goal of CGI::Ajax is to keep the module streamlined and maximally flexible. We are trying to keep the generated javascript code to a minimum, but still provide users with a variety of methods for deploying CGI::Ajax. And VERY little user javascript. periodt. π
π¦ EXAMPLES π¦
The CGI::Ajax module allows a Perl subroutine to be called asynchronously, when triggered from a javascript event on the HTML page. To do this, the subroutine must be registered, usually done during:
my $pjx = new CGI::Ajax( 'JSFUNC' => \&PERLFUNC );
This maps a perl subroutine (PERLFUNC) to an automatically generated Javascript function (JSFUNC). Next you setup a trigger this function when an event occurs (e.g. "onClick"):
onClick="JSFUNC(['source1','source2'], ['dest1','dest2']);"
where 'source1', 'dest1', 'source2', 'dest2' are the DIV ids of HTML elements in your page...
<input type=text id=source1>
<input type=text id=source2>
<div id=dest1></div>
<div id=dest2></div>
CGI::Ajax sends the values from source1 and source2 to your Perl subroutine and returns the results to dest1 and dest2. chef's kiss. π€
π 4 Usage Methods π
1 Standard CGI::Ajax example
Start by defining a perl subroutine that you want available from javascript. In this case we'll define a subrouting that determines whether or not an input is odd, even, or not a number (NaN):
use strict;
use CGI::Ajax;
use CGI;
sub evenodd_func {
my $input = shift;
# see if input is defined
if ( not defined $input ) {
return("input not defined or NaN");
}
# see if value is a number (*thanks Randall!*)
if ( $input !~ /\A\d+\z/ ) {
return("input is NaN");
}
# got a number, so mod by 2
$input % 2 == 0 ? return("EVEN") : return("ODD");
}
Alternatively, we could have used coderefs to associate an exported name...
my $evenodd_func = sub {
# exactly the same as in the above subroutine
};
Next we define a function to generate the web page β this can be done many different ways, and can also be defined as an anonymous sub. The only requirement is that the sub send back the html of the page. You can do this via a string containing the html, or from a coderef that returns the html, or from a function (as shown here)...
sub Show_HTML {
my $html = <<EOT;
<HTML>
<HEAD><title>CGI::Ajax Example</title>
</HEAD>
<BODY>
Enter a number:
<input type="text" name="somename" id="val1" size="6"
OnKeyUp="evenodd( ['val1'], ['resultdiv'] );">
<br>
<hr>
<div id="resultdiv">
</div>
</BODY>
</HTML>
EOT
return $html;
}
The exported Perl subrouting is triggered using the "OnKeyUp" event handler of the input HTML element. The subroutine takes one value from the form, the input element 'val1', and returns the the result to an HTML div element with an id of 'resultdiv'. Sending in the input id in an array format is required to support multiple inputs, and similarly, to output multiple the results, you can use an array for the output divs, but this isn't mandatory β as will be explained in the Advanced usage. π
Now create a CGI object and a CGI::Ajax object, associating a reference to our subroutine with the name we want available to javascript.
my $cgi = new CGI();
my $pjx = new CGI::Ajax( 'evenodd' => \&evenodd_func );
And if we used a coderef, it would look like this...
my $pjx = new CGI::Ajax( 'evenodd' => $evenodd_func );
Now we're ready to print the output page; we send in the cgi object and the HTML-generating function.
print $pjx->build_html($cgi,\&Show_HTML);
CGI::Ajax has support for passing in extra HTML header information to the CGI object. This can be accomplished by adding a third argument to the build_html() call. The argument needs to be a hashref containing Key=>value pairs that CGI objects understand:
print $pjx->build_html($cgi,\&Show_HTML,
{-charset=>'UTF-8, -expires=>'-1d'});
See CGI for more header() method options. (CGI.pm, not the Perl6 CGI) β important distinction bestie, don't get it twisted. π
That's it for the CGI::Ajax standard method. Let's look at something more advanced. β¨
2 Advanced CGI::Ajax example
Let's say we wanted to have a perl subroutine process multiple values from the HTML page, and similarly return multiple values back to distinct divs on the page. This is easy to do, and requires no changes to the perl code β you just create it as you would any perl subroutine that works with multiple input values and returns multiple values. The significant change happens in the event handler javascript in the HTML...
onClick="exported_func(['input1','input2'],['result1','result2']);"
Here we associate our javascript function ("exported_func") with two HTML element ids ('input1','input2'), and also send in two HTML element ids to place the results in ('result1','result2'). slay. π₯
3 Sending Perl Subroutine Output to a Javascript function
Occassionally, you might want to have a custom javascript function process the returned information from your Perl subroutine. This is possible, and the only requierment is that you change your event handler code...
onClick="exported_func(['input1'],[js_process_func]);"
In this scenario, "js_process_func" is a javascript function you write to take the returned value from your Perl subroutine and process the results. Note that a javascript function is not quoted β if it were, then CGI::Ajax would look for a HTML element with that id. Beware that with this usage, you are responsible for distributing the results to the appropriate place on the HTML page. If the exported Perl subroutine returns, e.g. 2 values, then "js_process_func" would need to process the input by working through an array, or using the javascript Function "arguments" object.
function js_process_func() {
var input1 = arguments[0]
var input2 = arguments[1];
// do something and return results, or set HTML divs using
// innerHTML
document.getElementById('outputdiv').innerHTML = input1;
}
4 URL/Outside Script CGI::Ajax example
There are times when you may want a different script to return content to your page. This could be because you have an existing script already written to perform a particular task, or you want to distribute a part of your application to another script. This can be accomplished in CGI::Ajax by using a URL in place of a locally-defined Perl subroutine. In this usage, you alter you creation of the CGI::Ajax object to link an exported javascript function name to a local URL instead of a coderef or a subroutine.
my $url = 'scripts/other_script.pl';
my $pjx = new CGI::Ajax( 'external' => $url );
This will work as before in terms of how it is called from you event handler:
onClick="external(['input1','input2'],['resultdiv']);"
The other_script.pl will get the values via a CGI object and accessing the 'args' key. The values of the 'args' key will be an array of everything that was sent into the script.
my @input = $cgi->params('args');
$input[0]; # contains first argument
$input[1]; # contains second argument, etc...
Okay bestie, so what if you need to send arguments to that other script that come directly from the calling Perl script? Like, you want a variable from your Perl script to get sent, NOT the value from some HTML element on the page? Totally doable with this syntax:
onClick="exported_func(['args__$input1','args__$input2'],
['resultdiv']);"
And similarly, if the external script needs a constant as input (like script.pl?args=42), you'd use this:
onClick="exported_func(['args__42'],['resultdiv']);"
In both of those examples, the result from the external script gets dropped into the resultdiv element on our page (the calling script's page, duh π).
Now, if you're sending more than one argument back from an external Perl script to a JavaScript function, you're gonna need to split that string somewhere β because AJAX apps only speak in strings, that's just the vibe. Internally, we use '__pjx__', and we check for that string. If it shows up, CGI::Ajax splits it automatically, no cap. But if '__pjx__' isn't your thing, you can absolutely do it yourself:
So like, from your Perl script you'd go...
return("A|B"); # join with "|"
and then in the JavaScript function you'd have something like...
process_func() {
var arr = arguments[0].split("|");
// arr[0] eq 'A'
// arr[1] eq 'B'
}
Wanna rename parameters? Say the outside script needs specifically-named parameters and not CGI::Ajax's default 'args' parameter name? Just change your event handler that's associated with an HTML event, like this:
onClick="exported_func(['myname__$input1','myparam__$input2'],
['resultdiv']);"
The URL that gets generated would look like this...
"script.pl?myname=input1&myparam=input2"
And you'd then retrieve the input in the outside script with this...
my $p1 = $cgi->params('myname');
my $p1 = $cgi->params('myparam');
Finally β and this is the β¨iconicβ¨ one β what if we need to grab a value from our HTML page and send it to an outside script, but that outside script requires a named parameter different from 'args'? You can pull this off with CGI::Ajax using the getVal() javascript method (it returns an array, hence the "getVal()[0]" notation, bestie):
onClick="exported_func(['myparam__' + getVal('div_id')[0]],
['resultdiv']);"
This grabs the value of our HTML element with an id of div_id, and submits it to the url attached to myparam__. So if our exported handler referred to a URI called script/scr.pl, and the element on our HTML page called div_id contained the number '42', then the URL would look like "script/scr.pl?myparam=42". The result from that outside URL gets placed back into our HTML page in the element resultdiv. There's a working example in the script that comes with the distribution called pjx_url.pl and its associated outside script convert_degrees.pl β go look at it, fr fr. π«Ά
N.B. These examples show the use of outside scripts which are other perl scripts β but you are not limited to Perl! The outside script could just as easily have been PHP or any other CGI script, as long as the return from the other script is just the result, and not additional HTML code (like FORM elements, etc).
π GET versus POST
So note that all the examples so far have used this syntax:
onClick="exported_func(['input1'],['result1']);"
There's an optional third argument to a CGI::Ajax exported function that lets you change the submit method. That same event could also have been coded like this...
onClick="exported_func(['input1'],['result1'], 'GET');"
By default, CGI::Ajax sends a 'GET' request. But if you need it β say your URL is getting wayyy too long β you can easily switch to a 'POST' request with this syntax...
onClick="exported_func(['input1'],['result1'], 'POST');"
('POST' and 'post' are both supported, lowercase girlies stay winning π
)
π§ Page Caching
We implemented a method to stop page cacheing from undermining the AJAX methods in a page. If you send in an input argument to a CGI::Ajax-exported function called 'NO_CACHE', then a special parameter gets attached to the end of your url with a random number in it. This will prevent a browser from caching your request. Obsessed.
onClick="exported_func(['input1','NO_CACHE'],['result1']);"
The extra param is called pjxrand, and it won't interfere with the order of processing for the rest of your parameters. π
Also see the CACHE() method for changing the default cache behavior.
π οΈ METHODS
build_html()
- Purpose: Associates a cgi obj (
$cgi) with pjx object, inserts javascript into<HEAD></HEAD>element and constructs the page, or part of the page. AJAX applications are designed to update only the section of the page that needs it β the whole page doesn't have to be redrawn. CGI::Ajax applications use thebuild_html()method to take care of this: if the CGI parameterfnameexists, then the return from the CGI::Ajax-exported function is sent to the page. Otherwise, the entire page is sent, since without anfnameparam, this has to be the first time the page is being built. - Arguments: The CGI object, and either a coderef, or a string containing html. Optionally, you can send in a third parameter containing information that will get passed directly to the CGI object
header()call. - Returns: html or updated html (including the header)
- Called By: originating cgi script
show_javascript()
- Purpose: builds the text of all the javascript that needs to be inserted into the calling scripts html
<head>section - Arguments:
- Returns: javascript text
- Called By: originating web script
- Note: This method is also overridden so when you just print a CGI::Ajax object it will output all the javascript needed for the web page.
register()
- Purpose: adds a function name and a code ref to the global coderef hash, after the original object was created
- Arguments: function name, code reference
- Returns: none
- Called By: originating web script
fname()
- Purpose: Overrides the default parameter name used for passing an exported function name. Default value is
"fname". - Arguments:
fname("new_name");# sets the new parameter name
The overriden fname should be consistent throughout the entire application. Otherwise results are unpredicted. π¬
- Returns: With no parameters
fname()returns the current fname name
JSDEBUG()
- Purpose: Show the AJAX URL that is being generated, and stop compression of the generated javascript, both of which can aid during debugging. If set to 1, then the core js will get compressed, but the user-defined functions will not be compressed. If set to 2 (or anything greater than 1 or 0), then none of the javascript will get compressed.
- Arguments:
JSDEBUG(0);# turn javascript debugging offJSDEBUG(1);# turn javascript debugging on, some javascript compressionJSDEBUG(2);# turn javascript debugging on, no javascript compresstion
- Returns: prints a link to the url that is being generated automatically by the Ajax object. this is VERY useful for seeing what CGI::Ajax is doing. Following the link, will show a page with the output that the page is generating.
- Called By:
$pjx->JSDEBUG(1)# where$pjxis a CGI::Ajax object;
DEBUG()
- Purpose: Show debugging information in web server logs
- Arguments:
DEBUG(0);# turn debugging off (default)DEBUG(1);# turn debugging on
- Returns: prints debugging information to the web server logs using
STDERR - Called By:
$pjx->DEBUG(1)# where$pjxis a CGI::Ajax object;
CACHE()
- Purpose: Alter the default result caching behavior.
- Arguments:
CACHE(0);# effectively the same as havingNO_CACHEpassed in every call - Returns: A change in the behavior of
build_htmlsuch that the javascript produced will always act as if theNO_CACHEargument is passed, regardless of its presence. - Called By:
$pjx->CACHE(0)# where$pjxis a CGI::Ajax object;
π BUGS
Follow any bugs at our homepage....
http://www.perljax.us
π SUPPORT
Check out the news/discussion/bugs lists at our homepage:
http://www.perljax.us
π AUTHORS
Brian C. Thomas Brent Pedersen
CPAN ID: BCT
bct.x42@gmail.com bpederse@gmail.com
significant contribution by:
Peter Gordon <peter@pg-consultants.com> # CGI::Application + scripts
Kyraha http://michael.kyraha.com/ # getVal(), multiple forms
Jan Franczak <jan.franczak@gmail.com> # CACHE support
Shibi NS # use ->isa instead of ->can
others:
RENEEB <RENEEB [...] cpan.org>
stefan.scherer
RBS
Andrew
Shoutout to every single one of them, honestly. π
π¦ A NOTE ABOUT THE MODULE NAME
This module was initiated using the name "Perljax", but then registered with CPAN under the WWW group "CGI::", and so became "CGI::Perljax". Upon further deliberation, we decided to change it's name to CGI::Ajax. Character development, honestly.
π COPYRIGHT
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
The full text of the license can be found in the LICENSE file included with this module.
π SEE ALSO
Data::Javascript CGI Class::Accessor
And that's the whole page, bestie!! π This was CGI::Ajax(3pm), served up from perl v5.34.0, dated 2022-06-09. Go forth and AJAX responsibly, mwah πβ¨
π¦ where this page comes from
- debian bookworm: libcgi-ajax-perl 0.707-3 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- debian trixie: libcgi-ajax-perl 0.707-3 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- ubuntu noble: libcgi-ajax-perl 0.707-3 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- ubuntu resolute: libcgi-ajax-perl 0.707-3 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- ubuntu stonking: libcgi-ajax-perl 0.707-3 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms