→ Ajax will_paginate, jq-style

25 December 2007

Matt Aimonetti has a Prototype-based Ajax Pagination in less than 5 minutes article showing how to unobtrusively Ajaxify will_paginate. Cool, but I don’t use RJS or Prototype anymore. I use jQuery.

Using jQuery, we too can easily rock some gracefully degrading Ajax pagination.

First step: ensure you’ve made your app jQuery Rails friendly. This’ll get our respond_to.js hooked up.

Next step: add a respond_to line in your controller:

def index
  @photos = Photo.paginate(:all,
    :conditions => { :user_id => current_user.id },
    :page => params[:page]
  )
  respond_to do |format|
    format.html # index.html.erb
    format.js { render :template => 'photos.html.erb' }
  end
end

We’re not using RJS, but we do want to respond to JS requests with some special sauce. In this case, we’re just rendering the layout-less bulk of our photos page.

With that done, it’s onto the javascript. We’re gonna use the LiveQuery plugin, which will re-apply behaviors to fresh HTML inserted into the DOM. In other words, the Ajax behavior we add to our will_paginate links will stick around between Ajax GET requests.

Grab it from Subversion:

$ wget http://jqueryjs.googlecode.com/svn/trunk/plugins/livequery/jquery.livequery.js

Be sure to include it in your layout:

<%= javascript_include_tag 'jquery', 'jquery.livequery.js,' 'application' %>

Finally, add this to your application.js:

jQuery(document).ready(function($) {
  $('div.pagination a').livequery('click', function() {
    $('#main').load(this.href)
    return false
  })
})

Sub the #main with whichever element you want replaced by our fresh photos.html.erb. And that’s it.