I have 1 more javascript file, now I want after adding a product to the cart successfully, I want to write an event. Now I want to know how to check when add to cart is successful to execute the next event in my javascript file
1 Answer
To check if add to cart is successful then add your event, you can use customerData to subscribe
to customerData.get('cart')
and check summary count.
To do this, take the following steps:
Step 1: Declare catalog-add-to-cart-mixin
config in requirejs-config.js
.
- File path: app/code/VendorName/ModuleName/view/frontend/requirejs-config.js
- Content:
var config = {
config: {
mixins: {
'VendorName_ModuleName/js/catalog-add-to-cart': {
'VendorName_ModuleName/js/catalog-add-to-cart-mixin': true
}
}
}
};
Step 2: Create catalog-add-to-cart-mixin.js
file.
- File path: app/code/VendorName/ModuleName/view/frontend/web/js/catalog-add-to-cart-mixin.js
- Content:
define([
'jquery',
'Magento_Customer/js/customer-data'
], function ($, customerData) {
'use strict';
var catalogAddToCartWidgetMixin = {
/** @inheritdoc */
_create: function () {
this._super();
this._doSomethingAfterAddedProductToCart();
},
_doSomethingAfterAddedProductToCart: function () {
var cartData = customerData.get('cart');
var currentCount = cartData()['summary_count'];
cartData.subscribe(function () {
if (currentCount !== undefined) {
if (cartData()['summary_count'] > currentCount) {
// do something here
console.log('Added a product to cart');
}
currentCount = cartData()['summary_count'];
}
});
}
};
return function (targetWidget) {
$.widget('mage.catalogAddToCart', targetWidget, catalogAddToCartWidgetMixin);
return $.mage.catalogAddToCart;
};
});
Step 3: Re-deploy static content
You're done.