Magento – How to update cart qty using ajax Magento 2

ajaxcartmagento2shopping-cart

How to update cart qty using ajax magento 2

I want to change qty on cart page.
I don't want to use the update button. It should be update automatically without reloading the page.

Best Answer

Reload totals cart after ajax change quantity 1. Step

In your custom them create ( Magento_Theme/layout/checkout_cart_index.xml )

<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="cart.ajax.qty.update"  template="Magento_Theme::js.phtml" after="-"/>
    </referenceContainer>
</body>

2.Step

creat js.phtml file ( Magento_Theme/templates/js.phtml )

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

3. Step create custom.js file in theme web folder ( Namespace/Yourtheme/web/js/custom.js )

    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);

                // The mini cart reloading
                customerData.reload(sections, true);

                // The totals summary block reloading
                var deferred = $.Deferred();
                getTotalsAction([], deferred);
            },
            error: function (xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                console.log(err.Message);
            }
        });
       });
      });
    });

4.Step ( map your js file )

Create requirejs-config.js on your theme root ( Namespace/yourtheme/requirejs-config.js)

var config = {
   map: {
    '*': {
        custom:'js/custom'
    }
  }
};

Now the qty update work using ajax If have any issue ask in comment.