Get started with jQuery, AJAX and JSON in your Perl web applications
May 22nd, 2009 by RohanIn this post I’ll go over a simple example on how to use jQuery with AJAX and JSON with your Perl web applications. I’ve used a plain-old CGI script along with Template Toolkit for this. However, you can very well use this under any web application framework. The main point is to get your concepts clear about how it all works.
First the demo - View it here
This example might not seem relevant to real-world applications, but its a good start to jQuery and JSON. Of course, you need to have some experience with jQuery. Don’t worry though, jQuery is amazingly simple to use once you get started on it. It does bite your ass couple of times, but once you understand the language, you’ll not be able to do without it.
This is the source code for the HTML template.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Perl, jQuery and JSON</title>
<script src="jquery-1.3.2.js"></script>
<link rel="stylesheet" type="text/css" media="all"
href="s.css" />
</head>
<body>
<div id="no_ajax">
<p>This form does not use AJAX/JSON. The submit will do a full page
refresh.
</p>
<form method="POST">
<button type="submit" name="submit_form" value="1">Get User Details</button>
</form>
[% IF user_details %]
<h3>User Details</h3>
Name: [% user_details.first_name _ ' ' _ user_details.last_name %]<br/>
Sex: [% user_details.sex %]<br/>
Age: [% user_details.age %]<br/>
[% END %]
</div>
<div id="use_ajax">
<p>This form uses jQuery. The submit will send a GET AJAX request and
will return a JSON object which we can use to update the div.
</p>
<button id="submit_form_ajax">Get User Details</button>
<span id="ajax_spinner" style="display: none;">
<img src="spinner.gif"/></span>
<div id="display_user_details">
</div>
</div>
<script>
// show the spinner for AJAX requests
$("#ajax_spinner").ajaxStart(function(){
$(this).show();
});
$("#ajax_spinner").ajaxStop(function(){
$(this).hide();
});
$("#submit_form_ajax").click(function(){
$("div#display_user_details").html('');
$.getJSON('?ajax=1', function(result){
$("div#display_user_details").html(
'<h3>User Details</h3>'
+ 'Name: ' + result.first_name + ' ' + result.last_name + '<br/>'
+ 'Sex: ' + result.sex + '<br/>'
+ 'Age: ' + result.age + '<br/>'
);
});
});
</script>
</body>
</html>
In lines 15-32 I define a form which will send a plain-old CGI request to the Perl script. The CGI script then does its stuff and returns the user details as a template variable which we then print out.
In lines 34-48 I define a second form (well, not really a form) which has just a single button. This button’s click event will be used to send an AJAX request using jQuery.
Now the fun part! Lines 52-58 set it up so that we can see a spinner image whenever any AJAX requests are sent.
In lines 60-72, we define a function for the click event of the button. In this function we call the getJSON jQuery method. The first parameter is the URL to which we append the ‘ajax=1′ query parameter, so the back-end CGI script knows that this is an AJAX request to be processed. The second argument to getJSON is a function which receives the JSON data sent back by the CGI script as its first argument. So, result is a javascript object which you can use like any other javascript object. I use the result object to populate the display_user_details div with the user info.
Now the Perl CGI script
#!/usr/bin/perl
use strict;
use warnings;
use JSON;
use Template;
use CGI;
my $q = CGI->new;
my $tt = Template->new(
INCLUDE_PATH => '.', # Path to template files
PRE_CHOMP => 0,
POST_CHOMP => 0,
);
my $tt_params;
# check form submit
if ( $q->param('submit_form') )
{
my $user_details = get_user_details();
$tt_params->{user_details} = $user_details;
}
# check if its an AJAX submit
if ( $q->param('ajax') ) {
my $user_details = get_user_details();
my $json = to_json($user_details);
print $q->header('application/json');
print $json;
exit;
}
print $q->header('text/html');
$tt->process( 'user_details.tt', $tt_params );
sub get_user_details
{
# pretend like we're doing some heavy task!
sleep 1;
my $user_details = {
first_name => 'Bob',
last_name => 'Green',
sex => 'M',
age => 35,
};
return $user_details;
}
If you’re familar with Template and CGI, this should be pretty simple to you.
The JSON stuff is in lines 25-31. get_user_details() returns a hashref which we convert to JSON data using to_json(). We first tell the browser that we’re sending JSON data in line 28, and then we send the JSON data. I’m using exit cause this is really a simple (not real world) example! In real world code, you would have all AJAX requests processed by a separate module so you can set the HTTP response headers in there, etc.
Again, do check out the demo, and hope you can now get started with using jQuery and JSON in your Perl web applications. Myself has a long way to go, but jQuery has really helped me a lot on the AJAX road.
Links

June 8th, 2009 at 2:50 am
Hello Rohan,
Thanks for the useful example. Can you put the s.css file somewhere too?
Sorry if I’m supposed to be able to figure out how to get it myself. I’m new to cgi programming and I don’t know how to get it myself yet…
Pat
June 9th, 2009 at 10:47 am
You can get the css file from -
http://aarohan.biz/demos/perl_jquery_example/s.css
June 25th, 2009 at 8:41 pm
very nice article. You have no idea how hard it is to find such an example on ajax and perl that is decent
June 26th, 2009 at 10:03 am
sorry another post, would you have an idea on how to get data from a form element. I have converted your code to be tied to a textfield instead of a button and when the user enters a letter on key up it does the jquery. What I am trying to do is pass the value, have the query check it with my database, and then return 0 or 1 for true or false and have the javascript do stuff with the boolean values. I am having problems getting that onchange data into cgi. Im using cgi::application and html::template. Would I have to tie it in the ajax url? I have spent all day on this and can’t figure it out, thanks, its very sweet.
March 27th, 2010 at 9:03 pm
Thank you very much for this article, it got me to understand the basics despite no previous experience with jquery and with AJAX at all.
For anyone using CGI::Application, I was able to get the Perl code running virtually as is by changing
line 62 of the HTML to
$.getJSON(’?a=ajax_test&ajax=1′, function(result){
where ajax_test is the name of my runmode.
May 6th, 2010 at 1:45 am
Thanks so much for your tutorials. JQuery is wicked once you understand the basic elements. Its just hard to find good noob tutorials. thank you