Magento 2: Update Item QTY in Cart Page Using AJAX

Adding quantity update on the cart page by using AJAX is one of the best methods to improve the user experience of your Magento 2 store.

By using the below steps, you can create your own simple module with the customization to add the AJAX functionality for updating the item quantity in your Magento 2 cart page.

Step 1:

In order to create a new extension in Magento 2, add a PHP file named registration.php like a file path given below,

Sample File Path: app/code/MyModule/AutoUpdateCartItemQty/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'MyModule_AutoUpdateCartItemQty',
    __DIR__
);

Step 2:

Create an XML file named module.xml like a file path given below to define your new module in Magento 2,

Sample File Path: app/code/MyModule/AutoUpdateCartItemQty/etc/module.xml

Here, you have to specify your custom module’s name like MyModule_AutoUpdateCartItemQty and it’s setup version as given below,

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="MyModule_AutoUpdateCartItemQty" setup_version="1.0.0">
    </module>
</config>

Step 3:

Create an XML file named checkout_cart_index.xml like a file path given below,

Sample File Path: app/code/MyModule/AutoUpdateCartItemQty/view/frontend/layout/checkout_cart_index.xml

In this file, you have to specify the template file of your custom module as follows,

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
     <body>
          <referenceContainer name="content">
               <block class="Magento\Framework\View\Element\Template" name="auto.update.cart.item.qty" template="MyModule_AutoUpdateCartItemQty::script.phtml" after="-"/>
          </referenceContainer>
     </body>
</page>

Step 4:

Create a phtml file named script.phtml like a file path given below,

Sample File Path: app/code/MyModule/AutoUpdateCartItemQty/view/frontend/templates/script.phtml

Here is the code for a script.phtml file which will be used to load your custom module js file in the checkout page,

<script>
    require ([
        'jquery'
    ],
    function ($) {
        $(window).on("load", function () {
            require([
               'MyModule_AutoUpdateCartItemQty/js/cartItemQtyUpdate'
            ]);
        });
    });
</script>

Step 5:

Finally, create a JS file named cartItemQtyUpdate.js like a file path given below,

Sample File Path: app/code/MyModule/AutoUpdateCartItemQty/view/frontend/web/js/cartItemQtyUpdate.js

In this file, add the following code which will be used to update the cart’s item quantity by using AJAX that while changing the value of qty field,

define([
    'jquery',
    'Magento_Checkout/js/action/get-totals',
    'Magento_Customer/js/customer-data'
], function ($, getTotalsAction, customerData) {
 
    $(document).ready(function(){
        $(document).on('change', 'input[name$="[qty]"]', function(){
            var form = $('form#form-validate');
            $.ajax({
                url: form.attr('action'),
                data: form.serialize(),
                showLoader: true,
                success: function (res) {
                    var parsedResponse = $.parseHTML(res);
                    var result = $(parsedResponse).find("#form-validate");
                    var sections = ['cart'];
 
                    $("#form-validate").replaceWith(result);
 
                    /* This is for reloading the minicart */
                    customerData.reload(sections, true);
 
                    /* This is for reloading the totals summary  */
                    var deferred = $.Deferred();
                    getTotalsAction([], deferred);
                },
                error: function (xhr, status, error) {
                    var err = eval("(" + xhr.responseText + ")");
                    console.log(err.Message);
                }
            });
        });
    });
});

After completing all the above steps run the below SSH command in your Magento 2 installed root directory,

php bin/magento setup:upgrade

Then, clear all the Magento cache and check the quantity update option in Magento 2 cart page.

Note: The above code has tested on Magento 2.3 with Luma theme.

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *