Magento 2 – Fix Error Cart Message on Ajax

jquerymagento2widget

My goal is to have a cart that live updates when you change the quantity's. Normally you need to press the 'update cart' button.

So I update my cart live by doing this:

require(['jquery', 'Magento_Customer/js/customer-data',
    'jquery/jquery-storageapi'], function ($) {
    // $("#submitbutton").hide();
    var form = $('form#form-validate');
    var qtyfields = $('input.qty');
    var increase = $('.meigee-arrow-right');
    var decrease = $('.meigee-arrow-left');
    increase.remove();
    decrease.remove();

    form.find(qtyfields).each(function (e) {


        $(this).change(function () {

            console.log('change detected');
            var thisfield = $(this);
            var datafield = thisfield.val();
            thisfield.attr('defaultValue', 'value');
            thisfield.html(datafield);
            TriggerAjax();


        });
    });

    function TriggerAjax() {
        $.ajax({
            url: form.attr('action'),
            data: form.serialize(),
            type: 'post',
            success: function (res) {
                form.submit();
                console.log('succes');
            },
            error: function () {
                console.log('error');
            }
        });
    }

    form.on('submit', function (e) {
        console.log('form submitted');
        e.preventDefault();
    });

    function LiveError() {
        console.log('test live error');
    }
});

And this works fine. I see the numbers change in my cart when the stock is there. The only thing is that the error message is not visible until I reload my cart page (the checkout/cart page).

Now i noticed that the form has data-mage-init='{"validation":{}}'

<form action="<?php /* @escapeNotVerified */ echo $block->getUrl('checkout/cart/updatePost') ?>"
          method="post"
          id="form-validate"
          data-mage-init='{"validation":{}}'
          class="form form-cart">

When I look closer at that Magento widget it does some kind of validation and sends it through ajax (i guess).

What I'm thinking is that it's not getting trigger until the page is reloaded so I'm not sure how to initiate this or make this happen.

Thanks in advance!

Best Answer

I tried your code and Ajax run fine but i cannot see the changes at same time. I see changes only when a page is loaded. Regarding message not showing, in my case when ajax request is going on this url:- http://XXX/Magento2.1.6/checkout/cart/updatePost/ then it throws 302 error because updatePost execute method returns $this->_goBack(). Since we are using ajax we can modify this to return a JSON so that request is updated successfully. For example, I modified it as

 public function execute()
{
    if (!$this->_formKeyValidator->validate($this->getRequest())) {
        return $this->resultRedirectFactory->create()->setPath('*/*/');
    }

    $updateAction = (string)$this->getRequest()->getParam('update_cart_action');

    switch ($updateAction) {
        case 'empty_cart':
            $this->_emptyShoppingCart();
            break;
        case 'update_qty':
            $this->_updateShoppingCart();
            break;
        default:
            $this->_updateShoppingCart();
    }

    echo 55; exit();/* can be anything which server correct ajax response*/
}

And it works and shows me error message though my price and other data are currently not updating(Might be this could be the reason):- enter image description here

Related Topic