N. Mauchle
N. Mauchle

Reputation: 504

Rails 4 ajax update div

I like to update a table with the new values using ajax. What is the idea. I have a cart, where the user can change the quantity of the product. I don't like to reload the whole page. I want to reload the table. At the moment it works with reloading the whole page.

What I have done.

I have a form for input a quantity value. To connect the product with a cart (ManyToMany) I uses line_item. So every line_item represents a product in a cart.

This view of the cart

<div id="cart_table">
  <%= render @cart %>
</div>

The render @cart

<table class="table  table-hover table-condensed">
  <tbody>
    <%= render cart.line_items %>
  </tbody>
</table>

Line_items with the update form:

<%= form_tag(line_item_path, method: "put", remote: true, class: "table_form") do %>
  <%= hidden_field_tag("product_id", value = line_item.product.id) %>
  <label>
    <%= number_field_tag "quantity", value = line_item.quantity, in: 1...11 %>
    <%= submit_tag "update", class: "btn btn-mini" %>
  </label>
<% end %>

The controller of line_items:

def update
    @cart = current_cart
    @line_item = @cart.update_product(params[:product_id], params[:quantity])
    respond_to do |format|
        if @line_item.save
            format.html { redirect_to current_cart, notice: 'Changed' }
            format.js
        else
            format.html { render action: "new" }
        end
    end
end

Here is where I get stuck. What I have to put in my update.js.rjs? Now I have this line

$('#cart_table').replaceWith("<%= escape_javascript(render @cart) %>");

But nothing happens and I get an error in the console:

send 
jQuery.extend.ajax 
$.rails.rails.ajax 
$.rails.rails.handleRemote 
(anonymous function) 
jQuery.event.dispatch 
elemData.handle

Would be nice to get some ideas to solve this little problem.

Thanks

Edit: It is better to use

$('#cart_table').html("<%= escape_javascript(render @cart) %>");

in the js file.

Upvotes: 2

Views: 9642

Answers (1)

Oleg Haidul
Oleg Haidul

Reputation: 3732

Try to use update.js.erb instead of update.js.rjs

Upvotes: 5

Related Questions