Magento – Update Cart Page by Ajax on quantity change

ajaxcartmagento-2.1.7

I have to update the main cart on change of quantity by Ajax without click on "Update Cart Button" and without reloading the page.
By the following code, I'm able to update cart table but m not getting a solution to update the "Cart Summary" block.

<script>
require(['jquery', 'Magento_Customer/js/customer-data',
    'jquery/jquery-storageapi'], function ($) {
    // $("#submitbutton").hide();
    var form = $('form#form-validate');
    var qtyfields = $('input.qty');
    $('.page.messages').each(function () {
        var thismessage = $(this);
        thismessage.attr('id', 'messages');
    });

    form.find(qtyfields).each(function (e) {
        var thisfield = $(this);
        $(this).change(function () {
            console.log('change detected');
            form.submit();
        });

    });
    form.on('submit', function (e) {
        e.preventDefault();
        $.ajax({
            url: form.attr('action'),
            data: form.serialize(),
            type: 'post',
            success: function (res) {
                var parsedResponse = $.parseHTML(res);
                var result = $(parsedResponse).find("#form-validate");
                $("#form-validate").replaceWith(result);
                //console.log(result);
                //location.reload();
            },
            error: function () {
                console.log('error');
            }
        });
        console.log('form submitted');
    });
});
</script>

Please give me some solution.

Best Answer

Use this one, it works fine for me:

  • var parsedResponse = jQuery.parseHTML(res);
  • var result = jQuery(parsedResponse).find(".subtotal");
  • var result1 = jQuery(parsedResponse).find(".message");
  • jQuery(".subtotal").replaceWith(result);
  • jQuery(".message").replaceWith(result1);