Magento 2 – Proper Way to Utilize ‘ajax:addToCart’ Event

addtocartjavascriptmagento2

I found the following codes in /vendor/magento/module-catalog/view/frontend/web/js/catalog-add-to-cart.js at around line 100, when I was trying to find ways to add some custom JS handling after successfully adding a product to the cart, on a Magento Open Source 2.2.5:

$(document).trigger('ajax:addToCart', {
    'sku': form.data().productSku,
    'form': form,
    'response': res
});

I believe this is the event I could utilize to achieve what I wanted. I have tried to write a handler like this inside the /product/view/form.phtml template:

<script>
require([
    'jquery'
], function ($) {
    $('document').on('ajax:addToCart', function (event, data) {
        console.log(data.form.data());
    });
});
</script>

But nothing showed up in the console. So I am guessing there is something wrong with the binding of handler and triggering of the event. Could someone please help to give an example on how I could make use of the event?

Best Answer

Yes, well, in the original code there is $(document), where document is js variable, but in your code you have something like $('document').

This is an attempt to select some DOM element I suppose, but maybe this selector is actually returning no selection and therefore nothing happens?

Final code is :

$(document).on('ajax:addToCart', function (event, data) {
    console.log(event);
    console.log(data);
});
Related Topic