Rob Hughes Rob Hughes - 5 months ago 116
jQuery Question

Ruby on rails - Load more button with kaminari and search form. Jquery problems

I have an ajax search form and ajax pagination using kaminari. I would like to change this into a 'load more' button but I'm having trouble with the jquery.

For the form and normal pagination I was using this in my index.js.erb ;

$('.gig-search-list').html("<%= j render(partial: 'gigs') %>");


This replaces all the current results with the new results from the search form, or the next page being selected with the kaminari gem.




I would like to have the 'load more' button add the results to the bottom of the page, but still have the search form behave as before.

With the example below, the 'load more' button works as desired, but the search form doesn't work at all.

$('.gig-search-list').append("<%= j render(partial: 'gigs') %>");





I then tried separating them....

$("#gig_search_form").submit(function() {
$('.gig-search-list').html("<%= j render(partial: 'gigs') %>")
$('#map').html('<%= j render("map") %>');
});

$(".pagination").click(function(){
$(".gig-search-list").append("<%= j render(partial: 'gigs') %>");
$('#map').html('<%= j render("map") %>');
});


This kind of works...a bit.... although I have to click twice, or submit the form twice to get the functions to fire. The pagination part doesn't take into account the search parameters and the search is all over the place too.




How can I combine the two functions? Use .html for the search form and .append for the pagination?

Answer

You can check condition in your index.js.erb, whether you got params[:page] or not.

eg. index.js.erb

<% if params[:page] %> #if clicked on load more, we will get params[:page]
 $('.gig-search-list').append("<%= j render(partial: 'gigs') %>");
<% else %>
 $('.gig-search-list').html("<%= j render(partial: 'gigs') %>");
<% end %>

When we click on pagination wee need to append results, so we can easily check that condition on js.erb

Comments