0

I have a form for filtering products, and want to change by AJAX the results on the partial for results:

<%= form_for :pin, url: filter_path, method: :get, remote: true do |f| %>
      <%= f.radio_button :category, category %>
      <%= f.range_field :max_value , type: "range", value: "1000", min: "1", max: "1000" %>
      <%= f.submit "Buscar", class: "margin_top width100" %>
<% end %>

In the controller, I respond to JS with a partial:

  respond_to do |format|
    format.js { render "filter_products" }
    format.html {render "index"}
  end

And lastly, on my filter_products.js, I change the partial with the new results:

$(document).ready(function(){
    var newProducts = '<%= j(render partial: "product_list", collection: @pins) %>';
    $("#product-list").replaceWith(newProducts);
});

Where product_list is my partial with the new products:

<% @pins.each do |pin| %>
    <%= render partial: "product_card", locals: {pin: pin} %>
<% end %>

Its working OK, but only the first time I submit the form. The second time on, its sending XHR requests with 200 responses, but it's not replacing the old products on the view.

Am I missing something?

Thanks!

Gibson
  • 2,055
  • 2
  • 23
  • 48

2 Answers2

0

The replaceWith wasn't working, instead, I used html.

 $("#product-list").replaceWith(newProducts);

to

 $("#product-list").html(newProducts);
Gibson
  • 2,055
  • 2
  • 23
  • 48
0

I think it's because Rails Turbolinks. Try to add https://github.com/kossnocorp/jquery.turbolinks

From documentation:

Gemfile:

gem 'jquery-turbolinks'

Add it to your JavaScript manifest file, in this order:

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//
// ... your other scripts here ...
//
//= require turbolinks
Zakhar Day
  • 401
  • 2
  • 3