0

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!

3
+50

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

  • Thanks for your comment. So you just changed the updatePost execute? Did you do this with a Plugin (think not since those have before/after/around) or did you do this in another way and how exactly? – CompactCode Aug 10 '17 at 13:04
  • This seems to work and i will comform this as an answer when i have replaced the controller and see if it still works. An important question -> Why the echo 55? – CompactCode Aug 10 '17 at 13:11
  • I did not use plugin i just do this to show u the solution, you can make changes according to your convenience but for me the reason was incorrect ajax response. – arushi Aug 10 '17 at 13:50
  • Ok i replaced the controller by adding a di.xml in etc/frontend with " <preference for="Magento\Checkout\Controller\Cart\UpdatePost" type="Designit\LiveUpdate\Controller\Cart\UpdatePost"/> " and changed what you did to that controller (if anyone wonders). It does seem to work fine now so i will add your response as a answer! Thanks! Just need to know what the echo 55 still is. – CompactCode Aug 10 '17 at 14:17
  • Ok nvm , the 55 i replaced with : $dataCart = $this->cart->getQuote()->getData(); echo json_encode($dataCart); exit(); and then i can JSON.parse what i want – CompactCode Aug 11 '17 at 2:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.