Pagination Using AJAX

Posted by Craig Ambrose on March 12, 2007 at 08:35 AM

The rails pagination helpers automatically give us a set of links to load different pages of a result set. Occasionally, you might not want to load these other pages of results as full page loads. There’s no reason why you can’t call an index action using AJAX, and have it respond with some javascript to update the list.

If you’re going to do this, you’ll need a different pagination helper. Since I’m such a nice guy, I’ve already written it for you.

The Code


def ajax_pagination_links(paginator, options={}, html_options={})
name = options[:name] || ActionView::Helpers::PaginationHelper::DEFAULT_OPTIONS[:name]
url_params = (options[:params] || ActionView::Helpers::PaginationHelper::DEFAULT_OPTIONS[:params]).clone links = pagination_links_each(paginator, options) do |n|
url_params[name] = n
link_to_remote(n.to_s, {:url => url_params, :method => :get, :loading => "Element.update('#{name}_loading_number', #{n}); Element.hide('#{name}_links'); Element.show('#{name}_loading')", :complete => "Element.show('#{name}_links'); Element.hide('#{name}_loading')"}, html_options)
end
loading_number = content_tag('span', '', :id => "#{name}_loading_number")
loading_spinner = image_tag 'spinner.gif'
loading = content_tag('div', "...loading page " + loading_number + ' ' + loading_spinner, :id => "#{name}_loading", :style => "display:none", :class => 'loading_text')
links_tag = content_tag('div', links, :id => "#{name}_links")
links_tag + loading
end

Usage

Simply wack that method in a relevant helper module, and use as in the following example:


<%= ajax_pagination_links @message_pages, :name => 'message_pages' %>

You only really need to specify the name option if there is going to be more that one of these in the current DOM and thus you’re going to hit problems with multiples of the same ID.

Also, I’ve referenced a spinner image. You may want to provide that, or pull the image tag bit out of the code.

Finally, I’ve added classes to things if you want to style it. I think it looks good with:


div.loading_text
{
color: #666;
}
Tags: (none)
Hierarchy: previous, next

Comments

There is 1 comment on this post. Post yours →

hi
Craig Ambrose
it’s an old post, but it’s useful to me. thx!!

Post a comment

Required fields in bold.