Mod_perl2, apache2.2, and CGI::Ajax notes…

Following along in my mod_perl2 notes, I wanted to document how to get CGI::Ajax working with mod_perl2. I hit a couple of snags along the way that are worth noting. First, the generated javascript for my functions was calling httpd? + vars, rather than my URI /modperl_handler/ajax? + vars. This was frustrating, but I determined that it was grabbing httpd from $0, so I changed it locally and the script worked after that. The second snag I hit was because I was instantiating my CGImodule globally instead of locally, and I would get segfaults now and then. Instantiating it inside the handler was the right way to go. Here is a working example:

package AjaxTest;

use CGI;
use CGI::Ajax;

use Apache2::RequestRec();
use Apache2::RequestIO();
use Apache2::Const -compile => qw(OK);

sub handler {
    my ($r) = @_;

    my $cgi = new CGI;  # had this outside the handler and was getting segfaults

    # Have to redefine $0 for CGI::Ajax because it's used to call further URLs from
    # javascript ajax functions.  (otherwise it did "httpd?"...)
    local $0 = $ENV{"REQUEST_URI"};
    $0 =~ s/?.*//;

    # Start Ajax stuff
    my $pjx = new CGI::Ajax("test_ajax" => &test_ajax);
    # Don't compress javascript (1 for user fcns only, 2 for all)
    # Send stderr to web logs

    print $pjx->build_html( $cgi, &base_page);
    return Apache2::Const::OK;

sub base_page {
    return "Ajax mod_perl testmod_perl 2.0.2 on apache 2.2.2 rocks! <p><div id="test">Change me</div><p>nn";

sub test_ajax {
    my $time = time();
    return "Test successful; $time<p>";

Share and Enjoy:
  • Print
  • Facebook
  • Twitter
  • PDF

Leave a Reply

Your email address will not be published. Required fields are marked *