ClearPress Framework

Working with Ajax

If you're not sure what AJAX is, in a nutshell it's the ability to load chunks of content behind-the-scenes using javascript. There are many, many other resources out there to tell you all about it, so I'm not going to attempt to do that here.

Using AJAX with ClearPress is pretty simple but we'll begin at the beginning. Let's assume you have a regular, non-AJAX-view for displaying information for a car manufacturer: package app::view::manufacturer; use strict; use warnings; use base qw(ClearPress::view); 1; This will use the default ClearPress read method and look for the manufacturer_read.tt2 template on disk when serving the /manufacturer/1 URI (for manufacturer 1 of course, and assuming you have a corresponding model with some data).

Luckily making use of the basic AJAX built-in to ClearPress is just as simple. The ClearPress view superclass contains support for read_ajax. What we'd like to do is display cars for that manufacturer without loading each page separately. We'll make another view class: package app::view::car; use strict; use warnings; use base qw(ClearPress::view); 1;

We'll import the most excellent jQuery library to take care of making our requests for us. In data/config.ini: [general] jsfile=http://code.jquery.com/jquery-1.4.1.min.js and in the manufacturer_read.tt2 template we'll add this: <ul> [% FOREACH car = model.cars %] <li> <a class="carlink" href="[% SCRIPT_NAME %]/car/[% car.id_car %]"> [% car.name %] </a> </li> [% END %] </ul> <div id="cartarget"> </div> <script type="text/javascript"> $(document).ready(function(){ $('a.carlink').click(function(){ $('#cartarget').load(this.href); return false; } } </script>

So what we're saying here is that when the document has finished loading, look for all anchors with a class of carlink and configure each so that when it's clicked it loads the anchor target into the cartarget div.

The eagle-eyed among you may have spotted that the /car/<id> page will normally load with full header & footer decoration but ClearPress is smart enough to detect the request is an AJAX one and serves the content without decoration.

The following static example demonstrates what this achieves.