5

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?

2

1 Answer 1

3

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);
});
1
  • Don't worry, it happens to all of us.
    – Marjan
    Sep 24, 2018 at 7:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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