It's been a few days that my team has been trying to make a will_paginate's infinite scroll work with a search that doesn't refresh the page, but so far we only managed to make either of them work, and it seems that the problem frustratingly lays in just one line of code...
# All of index.js.erb
$("#cards").html("<%= escape_javascript(render(@cards)) %>");
$("#cards").append('<%= j render(@cards) %>');
<% if @cards.next_page %>
$('.pagination').replaceWith('<%= j will_paginate(@cards) %>');
<% else %>
$(window).off('scroll');
$('.pagination').remove();
<% end %>
When that first line is removed, infinite scroll works nicely, but the search button adds the results to the next page, without removing the ones already on screen.
With that first line there, all the cards on screen are removed and new ones appear as expected with the first page of results, but the next pages aren't loaded at all with the infinite scroll.
Finally...
I believe that if there's a way to make that first line run only after the Search button is pressed, it will solve the problem, but we are really having a lot of problems to understand how .js.erb code works.
Some of the code that may or may not be relevant:
# Search button in index.html.erb
<%= form_tag(report_index_url, method: :get, remote: true) do %>
<div class="row">
<input id="search" name="search" class="..." type="search" >
<button onclick="topFunction()" class="..." type="submit"></button>
</div>
<% end %>
# Index method in report_controller
@cards = Card.from_user(@current_user.id)
apply_filters
execute_search
@cards = @cards.paginate(page: params[:page], per_page: 10)
respond_to do |format|
format.html
format.js
end
# Entire report.coffee
$ ->
if $('.pagination').length && $('#cards').length
$(window).scroll ->
url = $('.pagination .next_page').attr('href')
if url && $(window).scrollTop() > $(document).height() - $(window).height() - 60
$('.pagination').html('<img src="/assets/ajax-loader.gif" alt="Loading..." title="Loading..." />');
$.getScript(url)
$(window).scroll()