Resolving the Challenge of Duplicate Post Requests in Rails 3 Using Ajax

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!

Answer №1

If there is a double render issue, a DoubleRenderError would typically occur. It's important to verify that the JavaScript is not being initialized or called twice. Are you ensuring that the form doesn't submit to the same action? If it does, does it prevent the form submission in any way? The form appears to be submitted on blur - is it possible that selecting a value and pressing enter triggers the blur event and submits the form? Or perhaps the blur event is being triggered multiple times?

These are the initial areas I would investigate.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Parsley JS: A Solution for Distinct IDs

I have a form that contains multiple select boxes, and I need to ensure that no two select boxes have the same value selected. In simpler terms, if select box 1 is set to value 2 and select box 4 is also set to value 2, an error should be triggered. While ...

Deliver search findings that are determined by matching criteria, rather than by identification numbers

I am seeking to return a JSON match upon form submission, rather than simply searching for a specific ID. However, I am uncertain about how to structure this. I have the ability to search for the necessary match in a JavaScript document within one of my n ...

What are the steps to enable ajax communication with a database for posting, retrieving, and removing data?

Is there a way to utilize ajax for posting, deleting, and getting data from a database? I am looking to post content and then be able to delete it through the following link: (this is part of an assignment) However, I must use /ajax/addrecord.php and /a ...

Issue with Bootstrap checkbox/switch

Trying to determine the status of a checkbox - whether it's checked or not. The default state is unchecked, but I need to perform actions when it is checked and also when it gets unchecked. Currently using bootstrap 5.3.0 alpha html <div clas ...

ag-Grid - Automatically adjusting the height of detail section when data updates

I have implemented a table with a Master/Detail setup and I am utilizing the getRowHeight callback. Initially, the row height is set correctly. I expect that when the table data is updated, the row height for rows containing a detail grid should be recalc ...

Display hyperlinks upon hovering over text

In the sign-up form, there are options for two different types of users: teachers and students. When the sign-up option is selected, a drop-down menu with choices for teacher and student will appear. However, I would like it to function more like other w ...

Having trouble accessing functions within the webpack bundle

As someone new to the world of JS library development, I have embarked on a journey to achieve the following goals: Creating a library with TypeScript Generating a bundle using webpack5 Publishing the library to npm Utilizing the library in other projects ...

Is there a way to make this eval() function function properly in Internet Explorer?

My JavaScript code is fetching another JavaScript "class" from a different XHTML page. The fetched JavaScript looks like this: (function() { this.init = function() { jQuery("#__BALLOONS__tabs").tabs(); }; }) Once the f ...

What is the best way to make the button cover the entire width?

I have a Vuetify card with a layout where I am rendering some dynamic Vuetify components inside the card based on checkbox selection. These components can be a divider, a spacer, toolbar, or a button. However, I'm struggling to make the buttons span t ...

Turn off the observeChanges feature for the update query

I am trying to disable the observeChanges method on a collection when updating it. Does anyone have a solution for this? I came across the Meteor Docs which mentioned using reactive: false for the .find() method. Is there a similar option for the .update( ...

How can you incorporate AJAX to add a paragraph element to your HTML document?

I have encountered an issue with two files in my project. The first file is an HTML document, while the second file is a PHP file called ajax_access_database.php. Originally, I intended for the PHP file to access a database, but complications arose, leadin ...

Passing an array of integer arrays to a controller method in ASP MVC using Ajax

I am encountering an issue with my AJAX call when trying to post data entered by the user on the webpage to a controller method. Unfortunately, the data never reaches the controller and always results in an error. I suspect that the problem lies in the typ ...

Protractor: Configuration file failed to load

Upon the installation of protractor and initiation of selenium webdriver, I encountered an issue while attempting to run the config.js file located in the example folder of protractor. The error message "ERROR loading configuration file config.js" is displ ...

Modal not opening when activated from Foundation Foundation

I am encountering difficulty in triggering the Reveal modal, and I cannot figure out the issue. Initially, I suspected a JavaScript conflict. To troubleshoot, I stripped down the site to its essentials: some CSS, some JS, and some HTML. However, even afte ...

HTML experiences confusion as JSON tosses undefined data

Can someone assist me with API integration? I am new to this and trying to display the Poster, Title, and Year from an API URL. Here is the code I have been working on. When I log in, it shows JSON in an array but throws "undefined" in front-end. Your help ...

Transferring PHP data to JQuery through HTML elements

When adding a new comment to the list using PHP variables containing HTML code, the method of choice is typically through JQuery. The question arises - what is the most effective way to achieve this? Would one generally opt for an ajax call? Here's t ...

Encountering an error when trying to access a property of an undefined MVC model in a

Embarked on a journey to learn web service development, only to encounter a roadblock. I'm struggling to figure out how to utilize ExpressJS Router() to pass POST data to the controller files. Upon inspecting the request redirected from product.route. ...

Vue: Conditionally display a division depending on v-if, excluding cases where the div returns null

Within my HTML, I have implemented conditional rendering using v-if <div v-if="showdiv"> <p>Content 1 appears here</p> </div> <div v-if="!showdiv"> <p>Content 2 appears here</p> < ...

Pause server processing temporarily on datatables

I currently have a datatable that is populated with server-side data, which is functioning correctly. However, I now want to update the data rows by listening to notifications from AWS SQS. When a new row of data is received and added to the table API, cal ...

Select the top row of a table when the checkbox is ticked to emphasize it

Previously, I tackled a challenge on a webpage using jQuery where checkboxes in a table needed to be selected based on specific data attributes. Essentially, if one checkbox in a row was selected, the rest of the checkboxes would be disabled if their data ...