Using PJAX with Codeigniter
8 February 2013
We’re developing a new front-end for Tracks at the moment and have been researching various front end JS solutions. I’ve played around with both Backbone.js and Angular.js. Both are awesome (despite my JS noobness), but wasn’t convinced I needed this type of framework as of yet. Plus the learning curve (particularly Angular) is pretty steep.
Two key things in the redesign are that I don’t want pages to do full refreshes on say for example a filter change and I want the URL to change i.e. from ?foo=bar to ?foo=johndoe but without a reload. After looking at HTML5’s History API I stumbled upon PJAX (jQuery plugin that uses PushState), which I later found out 37signals used for the new Basecamp (good video here on David Heinemeier Hansson on using PJAX over Backbone.js).
This looked like a potential solution, particularly as it felt a bit easier to deploy. The only problem is there is not a great amount of support for using PJAX with PHP or Codeigniter, as it was originally built for Rails. However, this week I managed to get a prototype of the new interface working that allows me to sort deals, filter and change dates all without the page reloading and with the URL changing accordingly.
It. Is. Lightening. Fast.
Below is a summary of some of the code that I used to get PJAX working with Codeigniter. It’s no where near perfect, but should get you off on the right foot. I’ve not got a demo to share at the moment but stay tuned to the buildtracks.com blog for updates.
Main controller
function index()
{
// --- lots of code above this line ----
$data = $this->load->view('your_views', $some_date, true);
if (isset($_SERVER["HTTP_X_PJAX"])) {
echo $data['my_PJAX_data'];
} else {
$data = // construct header and footer and any other views as string
$this->load->view('main_view', $data);
}
}
main_view / your template
// display $my_PJAX_data
JS scripts
Tags & categories: codeigniter, jquery, pjax, angularjs, backbonejs, | Categories: Development,
Tweet