seanriordan08
seanriordan08

Reputation: 296

Rails 3 Ajax "Double Post Request" Issue

My Ajax is posting twice (while i'm expecting only once) on a click, and I can't seem to figure why. I think it may be a double render issue, but I'm pretty new to rails, and need some insight as to where?

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:

def create
 @cart = current_cart

 product = Product.find(params[:product_id])
 ctlQty = params[:qty_selected] #parameter from itemBoxZoom user selected quantity in jquery dialog widget
 @line_item = @cart.add_product(product.id, ctlQty) #passes in user selected quantity   

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

The method called 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 #removes unnecessary default value of 1
    end
end
qty_selected = nil
current_item
end

In my console, I see two almost identical post requests to LineItemsController#create, except while the 1st performs "INSERT INTO", the 2nd request performs "SET quantity = 2". All suggestions/help is SO much appreciated. Thanks

Upvotes: 0

Views: 1207

Answers (1)

davidfurber
davidfurber

Reputation: 5528

If it were a double render issue, you'd get a DoubleRenderError. Have you checked that the JavaScript isn't getting initialized/called twice? Does the form itself submit to the same action? If so, does it return false or otherwise cancel the form submission? I see that you are "submitting" the form on blur. I wonder if when you select the value and press enter, it triggers the blur event and submits the form? Or that the blur event is being triggered twice?

These are just the places I'd start looking.

Upvotes: 1

Related Questions