It’s often necessary to paginate in Ajax applications. For example, let’s say we have a tool for editors that lets them search for videos. The search is performed in one area and in an other area the user selects the page he wants to populate. Then he can just drag the chosen videos over the selected page. Full-page reload on pagination would be a problem, because the user would have to find the page he wants to edit again. We need to to able to paginate within the search results while leaving the rest of the page intact.
I did not want to implement pagination on the back end myself, so I took advantage of the mislaw-will_paginate gem.
The first task was to capture the pagination links. We render the links into a local variable like this:
@videos=Video.paginate :page=>params[:page]
pagination=ActionView::InlineTemplate.new("<%= will_paginate @videos %>", nil).render(@template, {})
The code to query the database would typically be more complicated, there would be chained named scopes, for example, and the call to ‘paginate’ would come last:
@videos=Video.most_popular.paginate :page=>params[:page]
We use JSON to communicate between the browser and the server. The video results are in an array generated by ActiveRecord. Let’s add the pagination string in the first position in the array:
@videos.unshift pagination # let's stick the pagination information in the first position
render({ :json => @videos.to_json(..) })
This does not disrupt the json encoding, the links stay a string while the rest of the array’s members get transformed according to the rules given in the to_json method.
On the JavaScript side, assuming that I have a div somewhere that looks like this:
<div id="pagination"> </div>
I can take resolve the pagination information and stick it to the div:
function onSearchResultsReady(results) {
var pagination=results.shift();
//processing here
// ..
$('#pagination').append(pagination);
ajaxifyLinks();
}
The final step is to prevent the browser from reloading the page so that it instead makes an Ajax call when the user clicks on a page link. Notice the call to ajaxifyLinks. That function overrides the links’ default behavior:
function ajaxifyLinks() {
$('#pagination a').click (function(){
$.getJSON(this.href,
{},
onSearchResultsReady);
return false; // don't follow the link
});
}
With minimal amount of work, we were able to make the gem do all the heavy-lifting, and even got our ajaxified pagination as well:
