How to Paginate With Ajax

Pagination is a very common task in web application development. But sometimes we need to paginate something with ajax request. The interest to use Ajax for this is to provide a dynamic interface which doesn’t need to reload the entire page when next results(page) displayed. Ajax is really nicely integrated with Rails, and using it is very easier with this great framework. To work with ajax requests your browser must be enabled to handled java script requests. I knew two methods for that problem.



First Method

Your Controller code


def ajax_pagination_links
@posts_pages, @posts= paginate :posts, :per_page => 3, :order=> “id DESC”
respond_to do |format|
format.html {render :partial=>”posts”,:layout=>”application”}
format.js {render :update do |page|
page.replace_html ‘total_posts’, :partial=>’total_posts’
page.visual_effect :highlight, “total_posts”
end}
end
end

Layout


<%= javascript_include_tag :defaults %>

View


<%= render :partial=>'total_posts' %>

_total_posts.rhtml


<% for post in @posts %>
<%= truncate(h(post.title.capitalize!),50) -%>
<%= truncate(h(post.description.capitalize!),50) -%>
<%end -%>
<%= link_to_remote 'Previous page',{:url=>{:action=>ajax_pagination_links, :page => @posts_pages.current.previous }, if @posts_pages.current.previous -%>
<%= link_to_remote 'Next page', {:url=>{:action=>ajax_pagination_links, :page => @posts_pages.current.next} if @posts_pages.current.next -%>

Second Method

Put this code in a helper somewhere


def ajax_pagination_links(paginator, options={})
options.merge!(ActionView::Helpers::PaginationHelper::DEFAULT_OPTIO NS) {|key, old, new| old}
window_pages = paginator.current.window(options[:window_size]).pages
return if window_pages.length <= 1 unless
options[:link_to_current_page]

first, last = paginator.first, paginator.last

returning html = '' do
if options[:always_show_anchors] and not window_pages[0].first?
html << link_to_remote(first.number, :update => options[:update], :url => { options[:name] => first }.update(options[:params] ))
html << ' ... ' if window_pages[0].number - first.number > 1
html << ' '
end

window_pages.each do |page|
if paginator.current == page && !options[:link_to_current_page]
html << page.number.to_s
else
html << link_to_remote(page.number, :update => options[:update], :url => { options[:name] => page }.update(options[:params] ))
end
html << ' '
end
if options[:always_show_anchors] && !window_pages.last.last?
html << ' ... ' if last.number - window_pages[-1].number > 1
html << link_to_remote(paginator.last.number, :update => options[:update], :url => { options[:name] => last }.update( options[:params]))
end
end
end

and use following code for creating links

View


<%= ajax_pagination_links @posts_pages, {:params => {:posts => @posts} } %>

Author-icon Published by : Satish Chauhan @ 01 Aug, 2007 at 04:49PM
Sponsored Links