Magento 2: Update Item QTY in Cart Page Using AJAX

Here is the small blog which helps to improve the user experience of your Magento 2 store by adding the quantity update option by using AJAX in the cart page.

Follow the below simple steps to create a new extension in Magento 2, which helps to add the AJAX functionality for updating the item quantity in your cart page.

Step 1:

Create a new php file named registration.php in the following file path,

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 a xml file named module.xml in the following file path to define the new module,

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

Here, we have to specify our custom module’s name like MyModule_AutoUpdateCartItemQty and it’s setup version as 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 a xml file named checkout_cart_index.xml in the following file path,

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

In this file, we have to specify the template file of our 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 in the following file path,

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 our 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 in the following file path,

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

In this file, we have to 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 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 the cart page.

Note: We have tested the above code on Magento 2.3 with Luma theme.

Hope this helps.

Leave a Reply

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