Мой Ajax отправляет дважды (пока я ожидаю только один раз) по щелчку, и я не могу понять, почему. Я думаю, что это может быть проблема с двойным рендерингом, но я довольно новичок в рельсах и мне нужно понять, где?Rails 3 Ajax «Double Post Request» Issue
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"
});
}
});
Контроллер:
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
Метод называется в моей модели:
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
В моей консоли я вижу две почти одинаковые почтовые запросы LineItemsController # create, за исключением того, что первый выполняет «INSERT INTO», второй запрос выполняет «SET quantity = 2». Все предложения/помощь так высоко ценятся. Спасибо
Я смог найти конкретное решение здесь: [http://stackoverflow.com/questions/8238599/jquery-click-fires-twice-when-clicking-on-label]. Все еще не уверен, почему «blur()» срабатывает дважды, но если здесь добавлен «evt» '$ (document) .ready (function (** evt **) {' и both 'evt.stopPropagation(); evt.preventDefault(); 'линии добавляются в функцию .blur()', она срабатывает только один раз! Возможно, дешевый взломать, но на данный момент мне все равно. – seanriordan08