Transcript
Page 1: Ajax pagination using j query in rails3

AJAX Pagination using jQuery in Rails3

Ajax pagination will do the same functionality of pagination without refreshing the page. It call 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 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) endend

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");

Page 2: Ajax pagination using j query in rails3

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 "<%= will_paginate(@posts ,:id=>"ajax_paginate") %>" will generate your pagination links

Voila, You are done!


Top Related