Monday, April 12, 2010

Make will_paginate as ajax pagination

Add below code in your public/javascripts/application.js

document.observe("dom:loaded", function() {
// the element in which we will observe all clicks and capture
// ones originating from pagination links
var container = $(document.body)

if (container) {
var img = new Image
img.src = '/images/spinner.gif'

function createSpinner() {
return new Element('img', { src: img.src, 'class': 'spinner' })
}

container.observe('click', function(e) {
if (e.element().match('img'))
var el = e.element().ancestors()[0]
else
var el = e.element()
if (el.match('.pagination a')) {
el.up('.pagination').insert(createSpinner())
new Ajax.Request(el.href, { method: 'get' })
e.stop()
}
})

}
})

In app/controllers/controller.rb file add below

def product

@similar_products = Product.paginate(:per_page => 4,:page=>params[:similar_products_page],:conditions => ["shopping_category_id = ? and id != ?", @product.shopping_category_id, @product.id])

@featureproduct = Product.paginate(:per_page =>1, :page=>params[:featureproduct_page], :conditions => ["featured = ? and id != ?", 1, @product.id], :order=>'rand()', :limit => 3)

if params[:similar_products_page]
respond_to do |format|
#format.html
format.js {
render :update do |page|
# 'page.replace' will replace full "results" block...works for this example
# 'page.replace_html' will replace "results" inner html...useful elsewhere
page.replace_html 'related', :partial => 'related_products'
end
}
end
end

if params[:featureproduct_page]
respond_to do |format|
#format.html
format.js {
render :update do |page|
# 'page.replace' will replace full "results" block...works for this example
# 'page.replace_html' will replace "results" inner html...useful elsewhere
page.replace_html 'featured', :partial => 'product_featured'
end
}
end

end
In app/views/products/_product_featured.rb
<%= will_paginate @featureproduct, :param_name => 'featureproduct_page', :prev_label => image_tag('shopping/left_arrow.jpg'), :next_label => image_tag('shopping/right_arrow.jpg'), :page_links=>false%>


In app/views/products/_related_products.rb
<%= will_paginate @similar_products,:param_name => 'similar_products_page' %>

Now your pagination become ajax.

0 comments: