WooCommerce - auto update total price when quantity changed
Replacing the default "Update Cart" button with an AJAX-driven approach allows for a smoother user experience, eliminating the full page reload. However, implementing this logic requires precise handling of state to ensure that changing the quantity of one product does not inadvertently affect others in the cart.
The core issue in your current implementation stems from how the JavaScript event listener captures the quantity value. In your jQuery code, you are selecting the input element with:
$( document ).on( 'change', '.quantity, input[type=number]', function() {
var qty = $( this ).val();
// ...
});
This selector targets all inputs on the page that match those criteria. When you attach a single event handler to the entire document, that single qty variable is shared across all instances of the input field. As soon as the user changes the quantity of the first product, the value stored in qty updates. If the user then clicks the second product's input before the previous AJAX request finishes or if the logic isn't scoped correctly, the handler might be referencing a stale or incorrect global state relative to the specific DOM element triggering the event.
To fix this, you must ensure that inside the event handler callback, this refers strictly to the element that triggered the event. While your current code does use $(this), the logic flow suggests that the value being sent is not correctly isolated per product instance in the context of multiple items.
Here is a robust way to structure the AJAX call using modern jQuery best practices, ensuring data isolation:
jQuery( function( $ ) {
if ( typeof wc_cart_params === 'undefined' ) {
return;
}
$( '.quantity input[type="number"]' ).on( 'change', function() {
// Use event.target to get the specific element that changed
var $input = $( this );
var qty = parseFloat( $input.val() || 0 );
// Check if the value is valid before proceeding
if ( isNaN( qty ) || qty <= 0 ) return;
// Optional: Add a visual indicator like a spinner or loader here
$.post( rf_cart_params.ajax_url, {
action: 'rf_update_total_price',
security: rf_cart_params.rf_update_total_price_nonce,
quantity: qty
}).done( function( response ) {
// Ensure you are replacing the correct container based on your specific cart layout
// Usually, WooCommerce injects into a specific ID or appends to a list.
$( 'div.cart_totals' ).replaceWith( response );
// Trigger custom event if needed for other JS modules
$( 'body' ).trigger( 'rf_update_total_price' );
}).fail( function() {
console.error( 'Failed to update cart quantity.' );
});
return false; // Prevent default form submission behavior
});
});
On the server side, your PHP function update_total_price looks fundamentally sound, provided it is hooked correctly into wp_ajax_rf_update_total_price. The logic using WC()->cart->get_cart() iterates through all items. However, a common pitfall when debugging "cross-talk" between products is how you are sending the data back to the client.
In your PHP code, you calculate totals and call woocommerce_cart_totals(). This function outputs HTML for the cart summary. If you are replacing a container with this output via .replaceWith( response ), ensure that the HTML structure matches exactly what the frontend expects, including any necessary IDs or classes that other scripts might be listening to.
Why the "Last Value" Error Occurs
If your total price calculation results in 9000 instead of 7000, it implies that the server received a quantity of 2 for the first item when it should have received 1. Since you are sending a single quantity variable via POST, the backend code assumes this value applies to every item if not explicitly mapped by item key.
Your PHP loop handles this correctly:
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
// ...
if ( ! isset( $_POST['quantity'] ) ) continue;
// ...
$quantity = apply_filters( 'woocommerce_stock_amount', preg_replace( "/[^0-9\.]/", '', filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT)) );
// ...
WC()->cart->set_quantity( $cart_item_key, $quantity, false );
}
The code assumes the POSTed quantity is a scalar value meant to apply to the specific item being interacted with. If your frontend sends 2 for Item A, then immediately changes Item B but hasn't updated the variable yet (due to asynchronous nature), or if the browser's history/state causes a cache issue, you might see this behavior. However, given your description of "using last value," it strongly suggests that the JavaScript event binding is not strictly isolated to the specific input element instance.
Ensure that no other scripts are manipulating the rf_cart_params object globally before your script runs, and verify that wc_cart_params contains the correct nonce for security checks. If you are using a custom cart layout where .quantity appears multiple times, ensure the selector doesn't accidentally capture inputs meant for add-ons or variable product options unless they are part of the same update cycle.
For developers maintaining legacy WooCommerce themes, remember that woocommerce_cart_totals() is deprecated in newer versions of WooCommerce. If you are updating to a modern version, you should replace the server-side output with direct AJAX responses that return JSON or HTML fragments compatible with the new cart structure, rather than relying on deprecated functions to render the summary table.