Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: 'Load More' button with Ajax & Kaminari

I would like to create a "load more" ajax pagination, with Kaminari. I'm using this code :

class BienvenueController < ApplicationController
  def index
    @articles = Admin::Article.page(1).per(2)
    respond_to do |format|
      format.html
      format.js 
    end
  end
end

# Bienvenue#index

<div class="container"  style="min-width:<%= @width %>px">
<%= render "shared/articles" %>
<%= link_to_next_page @articles, 'Load More', :remote => true, :id=>"load_more_link" %>

# Shared/articles

<% @articles.each do |a| %>
        <article class="<%= a.rubrique.color %>">
                <div class="sharing">
                    <%= image_tag "facebook-32.png" %>
                </div>
                <p class="color<%= a.rubrique.color %>"><i>Le <%= I18n.localize(a.created_at, :format => :long) %>  par David Perrotin</i></p>
                <h1><%= a.titre %></h1>
                <div class="excerpt">
                    <%= a.chapo.html_safe %>
                </div>
                <div class="image">
                    <%= image_tag a.mainphoto.url(:medium), :width=>"100%" %>
                </div>
                <div class="contenu">
                    <%= a.contenu.html_safe %>
                </div>
                <div class="readmore">
                    <%= link_to "Continuer la lecture", article_path(a) %>
                </div>
            </article>
        <% end %>

# index.js.erb

$('.container').append("<%= escape_javascript(render 'shared/articles')%>");
$('#load_more_link').replaceWith("<%= escape_javascript(link_to_next_page(@articles,    'Load More', :remote => true, :id=>'load_more_link'))%>");

But the problem is that when I click on "Load More", it always shows the two same articles, the partial is never refreshed with two more articles, like I would like.

like image 835
GrégoireC Avatar asked Apr 23 '13 14:04

GrégoireC


1 Answers

I just ran into an issue with this that might help others. Depending on your version of jQuery, don't use replaceWith on the #load_more_link in index.js.erb.

There is a regression (http://bugs.jquery.com/ticket/13401) that an empty replaceWith does nothing, so on the very last page of your set, the link_to_next will be empty, making the line: $('#load_more_link').replaceWith(''); and thus will not replace the last "more" button, so you'll continually load the last page of your data set.

Fixed by updating jQuery version or use empty().html('...') instead of replaceWith.

like image 115
Greg Olsen Avatar answered Sep 28 '22 05:09

Greg Olsen