jQuery + CodeIgniter

While working on streamlining the back end of our soon-to-be-launched Laborinth application, I went looking for a neat, tidy, and flexible AJAX interface for our controllers. There a number of solutions offered by the fabulous community over at the Codeigniter forums, but they all seem to be either limited in scope or rely on run-time generation of page-specific scripts—a major no-no in our “load-only-what-you-need” design philosophy.

To avoid page-specific code, we opted to load a (minified) library of javascript callbacks at runtime and move the burden of AJAX choreography to the server side. It ended up looking a little something like this:

  1. Potential callback functions are loaded with the page
  2. AJAX requests are processed controller-side, and a callback action and parameters are specified in the response
  3. The callback action is performed
jQuery(document).ready( function(){

    var _actions = {
        show_message: function( el, response ){ 

            el = $( el );
            el.fadeOut( 50, function() {
                $(response.message).fadeIn( 'fast' ).insertAfter( el );

    $('a.ajaxable').click( function(){

        var _el = this;

        $.post( this.href, function( result ){
            _actions[ result.action ]( _el, result );
        }, 'json');

        return false;
} );

In this example, each AJAX link (identified by the ajaxable class) is set up to post to a predetermined Controller URL. One of the attributes in the JSON object returned by $.post is the name of a callback action predefined in _actions. the complete JSON result object is passed to the callback as it is called, enabling us to pass parameters to the callback directly from our controllers.

The only thing left is to set up a controller function to generate the required JSON code and test it out. For our test, let’s use the simple replacement callback action to replace a clicked link with a success message.

    public function test() {

        header( 'Content-type: application/json' );

        echo json_encode( array( //requires php5

            'action' => 'show_message',
            'message' => '<div>Success! That worked out just fine.</div>',
        ) );

Create a link that points to test—let’s say that test() is in the welcome controller — and away you go!

<a href="<?php echo site_url('welcome/test'); ?>" class="ajaxable">click me!

I’m hoping to package it up someday on Github…someday…