Reputation: 886
I have followed this tutorial: Rails - load more results using jquery ajax but not sure where I am making a mistake or if something in the tutorial is wrong.
EDIT:
When i click "Load More": the ajax loader gif does not appear and the next 3 categories do not appear below the current 3 categories (with articles belonging to the category).
When i click "Load More": the ajax loader gif does appear and the next 3 categories do get rendered. However, they are overlaying over the current categories instead of being added below the current categories.
categories/index.html.erb
<div class = "container">
<%= render @categories %>
</div>
<div class="load-more-container">
<%= image_tag "ajax-loader.gif", style: "display:none;", class: "loading-gif" %>
<%= link_to "Load More", categories_path, class: "load-more" %>
</div>
<script>
$('.carousel').carousel({
interval: false
});
</script>
_category.html.erb
<div class="category" data-id="<%= category.id %>">
<h3 class= "padding-bottom-20"><%= link_to category.name, category_path(category) %></h3>
<% div_id = "carousel_slider_#{category.id}" -%>
<div id="<%= div_id -%>", class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="item active">
<div class="carousel-content">
<%= render 'article', obj: category.articles.order("impressions_count DESC").limit(3) %>
</div>
</div>
<div class="item">
<div class="carousel-content">
<%= render 'article', obj: category.articles.order("impressions_count DESC").limit(3).offset(4) %>
</div>
</div>
</div>
<a class="left carousel-control" href="#<%= div_id -%>" + "#{category.name}" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
<a class="right carousel-control" href="#<%= div_id -%>" + "#{category.name}" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</div>
</div>
Categories controller
class CategoriesController < ApplicationController
before_action :authenticate_user!
def index
if params[:id]
@categories = Category.order('created_at DESC').where('id < ?', params[:id]).limit(3)
else
@categories = Category.order('created_at DESC').limit(3)
end
respond_to do |format|
format.html
format.js
end
end
end
assets/javascripts/category.js
$(document).ready(function () {
$('a.load-more').click(function (e) {
e.preventDefault();
$('.load-more').hide();
$('.loading-gif').show();
var last_id = $('.category').last().attr('data-id');
$.ajax({
type: "GET",
url: $(this).attr('href'),
data: {
id: last_id
},
dataType: "script",
success: function () {
$('.loading-gif').hide();
$('.load-more').show();
}
});
});
});
categories/index.js.erb
$('.container').append('<%= escape_javascript(render(:partial => @categories)) %>')
Upvotes: 1
Views: 131
Reputation: 886
Change index.html.erb to
<div id="category">
<%= render @categories %>
</div>
index.js.erb
$('#category').append('<%= escape_javascript(render(partial: @categories)) %>')
Upvotes: 1