Help! My Ajax is triggering twice when I only want it to happen once. I have a feeling it might be due to a double render issue, but I'm new to Rails and could really use some guidance on where to look for a solution.
Here's the JS:
$("select[name='order[city]']").on("blur",function() {
$("#triangle").fadeOut(800);
$("#cityFee").fadeOut(800);
if (feeSelected == 80 || feeSelected == 81){
$.ajax({
type: "POST",
url: '/line_items',
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
data: {product_id: feeSelected, qty_selected: 1, remote: true},
dataType: "script"
});
}
});
The Controller looks like this:
def create
@cart = current_cart
product = Product.find(params[:product_id])
ctlQty = params[:qty_selected]
@line_item = @cart.add_product(product.id, ctlQty)
respond_to do |format|
if @line_item.save
format.html { redirect_to(store_index_url) }
format.js { @current_item = @line_item }
format.json { render json: @line_item, status: :created, :location => @line_item }
else
format.html { render :action => "new" }
format.json { render json: @line_item.errors, status: :unprocessable_entity }
end
end
end
This is the method in my Model:
def add_product(product_id, qty_selected)
current_qty = qty_selected || 1
current_item = line_items.find_by_product_id(product_id)
if current_item
current_item.quantity += current_qty.to_i
else
current_item = line_items.build(:product_id => product_id)
if qty_selected
current_item.quantity += current_qty.to_i - 1
end
end
qty_selected = nil
current_item
end
When I check my console, I notice that there are two similar post requests to LineItemsController#create. The first request performs "INSERT INTO" while the second request performs "SET quantity = 2". Any suggestions or help would be greatly appreciated. Thank you!