How to add AJAX Pagination using jQuery in Rails3

ror1 150x150
Social sharing

Ruby_on_railsAjax pagination will do the same functionality of pagination without refreshing the page. It calls the action through jQuery to display the results per page.

This example demonstrates the implementation of ajax pagination in Rails3. However the same can be used with Rails2.3.x.

Remember to add jQuery to your paths.

Step#1

Add the following gem to your Gemfile

gem 'will_paginate'
Run bundle install

Step#2

Include the following code in the controller you want to paginate, For example, I have used Posts controller.

class PostsController < ApplicationController
  def index
    @posts = Post.paginate(page: params[:page], per_page: 10)
  end
end

Step#3

Add this in the view “posts/index.html.erb” file

<div id=”post_id”>
<%=render partial:’posts’%>
</div>

Encapsulate the order list in the partial view “posts/_posts.html.erb”

<ul>
<% @posts.each do |post|%>
<li>
<!-- Show post data -->
</li>
<% end %>
</ul>
<% = will_paginate(@posts,:id=>”ajax_paginate”)%>
 
<script>
 
$(document).ready(function() {
$(“#ajax_paginate”).find(“a”).each(function(){
var linkElement = $(this);
var paginationURL = linkElement.attr(“href”);
linkElement.attr({“url”:paginationURL, “href”: ”#”});
linkElement.click(function(){
$(“#post_id”).html(‘<div align= “center”><br/>
<img src=”/images/loader.gif”/></div>’)
$(“#post_id”).load($(this).attr(‘url’));
Return false;
});
});
});
 
</script>

The last line “”ajax_paginate”) %>” will generate your pagination links

Voila, You are done!

Your recently viewed posts:

Jayadev Das - Post Author

Do what you do best in – that’s what I’ve always believed in and that’s what I preach. Over the past 25+ years (yup that’s my expertise ‘n’ experience in the Information Technology domain), I’ve been consulting to small, medium and large companies ‘About Web Technologies, Mobile Future as well as on the good-and-bad of tech. Blogger, International Business Advisor, Web Technology Expert, Sales Guru, Startup Mentor, Insurance Sales Portal Expert & a Tennis Player. And top of all – a complete family man!

    Contact Us

    We’d love to help & work with you




    When do you want to start ?


    Enter your email address to stay up to date with the latest news.
    Holler Box

    Orange Exit pop up

    Subscribe for the latest
    trends in web and
    mobile app development
    Holler Box

    Exit pop up

    Sad to see you leaving early...

    From "Aha" to "Oh shit" we are sharing everything on our journey.
    Enter your email address to stay up to date with the latest news.
    Holler Box