5% assure discount from here only

Monday, March 28, 2011

(24) How to use CGI::Ajax with perl code?

Solution:

A cpan module CGI::Ajax is available to make the use of Ajax in your web application. It is an object-oriented module that provides a unique mechanism for using perl code asynchronously from javascript- enhanced HTML pages.

A very simple example of CGI::Ajax :-

#!/usr/bin/perl -w

use strict;
use CGI;

use CGI;
use CGI::Ajax;

my $cgi = new CGI;

my $pjx = new CGI::Ajax('checkname' => \&checkname);
print $pjx->build_html( $cgi, \&ajax_html);


sub checkname{
    my $input = shift;
    my $output = $cgi->param('name');
    return $output;
}

sub header {

    my $header = qq~<HTML>
            <HEAD>
            </HEAD>
            <BODY>~;
    return $header;
}

sub ajax_html{
  
    my $html_header = header();
    my $html_footer = footer();
  
    my $html_body = qq~<input type="button" value="Click Me" onclick="checkname(['name__lalit'], ['lalitdiv']);">
        <div id="lalitdiv">Ajaxx</div>~;

    my $full_html = $html_header.$html_body.$html_footer;

    return $full_html;
}

sub footer{
  
    my $footer = qq~</BODY>
    </HTML>~;
    return $footer;

}