One of my favourite components in Zend Framework is the AjaxContext action helper. This little beauty allows you to intercept AJAX requests and deliver a different view based on request parameters, all without touching a single line of action code.

One scenario where this has always appealed to me is in paginating data. Why reload an entire document each time you page through a dataset when you can use AJAX to fetch just the next page.

Now introduce the HTML5 History API, and all of a sudden you’ve got AJAX data updates with navigable, bookmarkable URLs.

In this article, I’m going to step through creating a paging controller action that updates the paged data via AJAX and maintains URL location for browsers that support the History API.

If you want to play along at home, all code used in this demo is available on github, with each stage represented by its own branch. Get the code at https://github.com/philBrown/Awesome-Pagination-Demo and checkout the “html-only” branch

git clone git://github.com/philBrown/Awesome-Pagination-Demo.git
cd Awesome-Pagination-Demo
git checkout -b origin/html-only

To start with, we have a vanilla ZF project with a layout and simple controller action that instantiates a paginator object (using the array adapter for this demo), grabs the “page” parameter from the request and assigns the paginator to the view.

public function indexAction()
{
    $paginator = Zend_Paginator::factory($this->getModels());
    $paginator->setCurrentPageNumber($this->getRequest()->getParam('page', 1));
    $this->view->paginator = $paginator;
}

Our view then displays the paginationControl helper

<?php $paginationControl = $this->paginationControl(
    $this->paginator, 'All', '_partials/paginator.phtml') ?>
 
<div class="pagination-control">
    <?php echo $paginationControl ?>
</div>

and a table with our data, looping over each item in the paginator.

What we end up with is something like this

Clicking on each paginator link loads an entirely new page with the requested data. Not horrible, but could be better.

Now checkout the “ajax-loading” branch

git checkout -b origin/ajax-loading

Our layout now includes the inlineScript helper with a link to jQuery on the Google CDN. The controller now initialises the AjaxContext helper to allow “html” AJAX requests for the index action.

public function init()
{
    $this->_helper->ajaxContext->addActionContext('index', 'html')
                               ->initContext();
}

The view has also been changed. We’ve added a link to our pagination JavaScript file (more on this later) and the guts of the view (pagination controls and data) has been moved into a new file index.ajax.phtml which is referenced using the render method.

// index.phtml
<?php $this->inlineScript()->appendFile('js/paginator.js') ?>
 
<div class="paged-data-container">
    <?php echo $this->render('index/index.ajax.phtml') ?>
</div>

The index.ajax.phtml file is the one delivered via the AjaxContext helper when an XMLHTTPRequest is intercepted with the “html” format parameter present. Including it in the default template caters for the first page load.

Now on to our JavaScript file. All this file needs to do is catch click events on any of the paginator links and fetch the contents via AJAX, repopulating the paginator controls and data.

In essence, it looks like this.

jQuery(function($){
    $('.pagination-control').find('a').live('click', function(){
        var link = $(this);
        var container = link.parents('.paged-data-container');
        $.get(link.attr('href'), { format: 'html' }, function(data){
            container.html(data);
        }, 'html');
        return false;
    });
});

We’re using the “live” binding as each AJAX load replaces the paginator controls. The { format: 'html' } parameter is added to the request to trigger the right context switch in the controller.

So now we have a basic AJAX paginator. The only problem here is that each page loads under the same URL. There’s also little visual feedback to let the user know the data is changing.

Taking a leaf out of GitHub’s “Tree Slider”, if you checkout the “ajax-loading-animations” branch, you’ll see some nifty left (next) and right (previous) scrolling.

So now we come to the final stage, utilising the HTML5 History API to add stateful URLs for each AJAX data load.

Checkout the master branch to see the code.

The gist of this is to use the history.pushState method to add history records on click and bind an event handler to the “popstate” event to catch navigation (back / forward) button presses.

The end result looks like this – http://apps.philipbrown.id.au/awesome-pagination/

Whilst it’s certainly not as snazzy as GitHub’s Tree Slider, it’s a step in the right direction.