CD-RUM CD-RUM - 5 months ago 112
jQuery Question

Rails: remote: true from select_tag

I'm calling an AJAX function from a

select_tag
like so:

<%= select_tag 'quantity', options_from_collection_for_select(order.options), :quantity, :quantity, order.quantity), onchange: "update_price(#{order.id}, this.value);" %>


And here's the function:

<script type='text/javascript'>
function update_price(order_id, quantity) {
$.ajax({
url: "/cart/" + <%= @cart_transaction.id %> + "/update_quantity",
type: "POST",
data: {
"order_id" : order_id,
"quantity" : quantity },
dataType: "html"
});
}
</script>


My
.js.erb
isn't called ever, and I suspect it's because I haven't specified
remote: true
anywhere, but since I don't have a form per se I don't know how to do that. Any help?

Relevant controller code here:

class CartTransactionsController < ApplicationController
load_and_authorize_resource

respond_to :html, :js

before_filter :set_cart_transaction

def update_quantity
@order = @cart_transaction.orders.find(params[:order_id])
@price = current_user.brand.prices
.where(template_id: @order.document.template.id)
.where(quantity: params[:quantity]).first
@order.update_attributes(
price_cents: @price.amount_cents, quantity: params[:quantity]
)
@cart_transaction.save!
respond_to { |format| format.js }
end

private

def set_cart_transaction
@cart_transaction = current_user.cart
end

def cart_transactions_params
params.require(:cart_transaction).permit(
:name, :email, :delivery_address, :comments
)
end
end


Update

Here's the
.js.erb
that isn't called for some reason:

console.log("update_quantity.js.erb file");

$('#price_cell').html("<%= j render(partial: 'price', locals: { order: @order }) %>");
$('#subtotals').html("<%= j render(partial: 'subtotals', locals: { cart_transaction: @cart_transaction }) %>");

Answer

Try this:

function update_price(order_id, quantity) {
    $.ajax({
      beforeSend: function(xhr) {
        xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
      },
      url: "/cart/" + <%= @cart_transaction.id %> + "/update_quantity",
      type: "POST",
      data: {
        "order_id" : order_id,
        "quantity" : quantity }
    });
  }