In 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
- jQuery
- JSON on CPAN
- Template Toolkit on CPAN
Tweet This Post
Facebook