Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get will_paginate working with Ajax

If you google "will_paginate" and "ajax", the top result is this blog post: But the original author of will_paginate says to not use this method (bad for SEO/spiders) ...

But I cant get the original authors method to work (his javascript kills all my links). An other gentleman suggests a similar method to mislav's (the original will_paginate author) concept. But I cant get that to work either.

so .... what is the best way to paginate using AJAX, and stay SEO friendly? (for RAILS >2.1)

like image 241
Etienne Avatar asked Feb 19 '09 12:02

Etienne


1 Answers

Tomh's answer is correct. Just for shiggles, I prototyped a quick implementation. Here's a screencast that shows it using Ajax when Javascript is enabled (your users) and still having pretty URLs when Javascript is disabled (Google). And here are a few code snippets to get you rolling on it.

config/routes.rb:

map.connect 'items/:page', :controller => "items", :action => "index", :page => 1

app/controllers/items_controller.rb:

class ItemsController < ApplicationController
  def index
    @items = Item.paginate(:all, :page => params[:page])

    respond_to do |format|
      format.html
      format.js do
        render :update do |page|
          page.replace_html :items, :partial => "items"
          page << "ajaxifyPagination();"
        end
      end
    end
  end
end

app/views/items/index.html.erb:

<h1>Listing items</h1>

<div id="items">
  <%= render :partial => "items" %>
</div>

app/views/items/_items.html.erb:

<%= will_paginate @items %>

<table>
  <% for item in @items %>
    <tr>
      <td><%= item.id %></td>
    </tr>
  <% end %>
</table>

layout:

<%= javascript_include_tag :defaults %>

public/javascripts/application.js:

$(document).ready(function() {
    ajaxifyPagination();
});

function ajaxifyPagination() {
    $(".pagination a").click(function() {
        $.ajax({
          type: "GET",
          url: $(this).attr("href"),
          dataType: "script"
        });
        return false;
    });
}

My example uses jQuery (with jRails), but it's straightforward to do with Prototype as well.

like image 123
Ian Terrell Avatar answered Oct 21 '22 11:10

Ian Terrell