Magento2 – Catch Ajax Complete and Add to Cart

addtocartajaxjquerymagento2mini-cart

I'm building an custom mini-cart. I want it to update itself when an article is added to the cart. I'm trying to do this by jQuery with catching the ajax complete, but can't get it to work. Can anyone help me?

Best Answer

To implement this you must override or extend the core catalog-add-to-cart.js file from your module. I assume that you know how to create a module. Create requirejs-config.js file at /var/www/html/YOURMAGENTOSTORE/app/code/Vendor/Module/view/frontend/requirejs-config.js.

var config = {
    map: {
        '*': {
            'catalogAddToCart':
                'Vendor_Moduel/js/catalog-add-to-cart'
        }
    }
};

Now copy the core file from Magento_Catalog/view/frontend/web/js/catalog-add-to-cart.js to your file at /var/www/html/YOURMAGENTOSTORE/app/code/Vendor/Module/view/frontend/web/js/catalog-add-to-cart.js. Now the part of your interest will be the function named ajaxSubmit.

ajaxSubmit: function(form) {
    var self = this;
    $(self.options.minicartSelector).trigger('contentLoading');
    self.disableAddToCartButton(form);

    $.ajax({
        url: form.attr('action'),
        data: form.serialize(),
        type: 'post',
        dataType: 'json',
        beforeSend: function() {
            if (self.isLoaderEnabled()) {
                $('body').trigger(self.options.processStart);
            }
        },
        success: function(res) {
            if (self.isLoaderEnabled()) {
                $('body').trigger(self.options.processStop);
            }

            if (res.backUrl) {
                window.location = res.backUrl;
                return;
            }
            if (res.messages) {
                $(self.options.messagesSelector).html(res.messages);
            }
            if (res.minicart) {
                $(self.options.minicartSelector).replaceWith(res.minicart);
                $(self.options.minicartSelector).trigger('contentUpdated');
            }
            if (res.product && res.product.statusText) {
                $(self.options.productStatusSelector)
                    .removeClass('available')
                    .addClass('unavailable')
                    .find('span')
                    .html(res.product.statusText);
            }
            console.log('yes added my code');

            self.enableAddToCartButton(form);

        }
    });
},

You need to do whatever you want at the success section of it.

The output of my console is:

yes added my code

As you can see that you will be able to catch the ajax success event by this method.