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
Layout
View
<%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
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
Do you have a working example on the web somewhere? I was browsing around trying to solve this issue. Thanks,
Hank