In Magento 2, updating shipping rates/shipping methods dynamically is a common requirement when customers change cart items. If a customer modifies the quantity or removes a product, the shipping options may also need to be recalculated.
In this blog, I will explore how you can recollect the shipping rates programmatically using Magento 2’s built-in JavaScript method in a simple and easy-to-understand way.
Why Recollect Shipping Rates Dynamically?
Suppose, you have implemented some Ajax call in the cart page and modified something like item qty or other items-related data using that Ajax call, then to ensure customers always see accurate shipping options, you may required to recollect/update shipping rates.
Recollecting shipping rates ensures that customers are always presented with up-to-date shipping options, avoiding potential checkout errors or inaccurate shipping costs.
Magento 2 provides an API for developers to trigger the recalculation of shipping rates using the Magento_Checkout/js/action/recollect-shipping-rates
module. Let’s dive into how to integrate this functionality.
Sample Code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
define([ 'jquery', 'Magento_Checkout/js/action/get-totals', 'Magento_Checkout/js/action/recollect-shipping-rates', 'Magento_Customer/js/customer-data' ], function ($, getTotalsAction, recollectShippingRates, customerData) { 'use strict'; return function () { // Listen for quantity change in cart $(document).on('change', 'input[data-role="cart-item-qty"]', function () { var form = $('form#form-validate'); // Send an AJAX request to update the cart $.ajax({ url: form.attr('action'), data: form.serialize(), type: 'POST', showLoader: true, success: function () { // Recollect the shipping rates after cart is updated recollectShippingRates(); // Refresh cart totals getTotalsAction([], $.Deferred()); // Reload the minicart to reflect the changes customerData.reload(['cart'], true); } }); }); }; }); |
When a customer changes the quantity of an item in the cart, the script sends an AJAX request to update the cart.Once the cart is updated, the shipping methods are recollected based on the new cart total.The minicart is reloaded, and the cart totals are refreshed automatically.
By using this simple approach, you can ensure that when a customer updates the quantity of an item in their cart, the shipping rates are recollected dynamically. This method enhances the user experience and ensures accurate shipping options without requiring a page reload.
For more Magento 2 tutorials, keep following my blog!
People also searched for
Dynamically Update Cart Totals in Magento 2
Magento 2 AJAX Cart Quantity Update
How to Refresh Cart Totals After Update in Magento 2
Update shipping methods after Ajax call on the cart page
You may also like :
How to Get Admin URL in Magento 2