How can I show Add to Cart success message ("You added 'Product name' to your shopping cart.") in a popup in Magento 2?
2 Answers
Copy catalog-add-to-cart.js from core '\module-catalog\view\frontend\web\js/catalog-add-to-cart.js and place into your theme folder \Package/theme/Magento_Catalog/web/js/catalog-add-to-cart.js
Now find ajaxSubmit function and add below code after self.enableAddToCartButton(form);
var popup = $('<div class="add-to-cart-dialog"/>').html($('.page-title span').text() + '<span> has been added to cart.</span>').modal({ //get product name from product view page only
modalClass: 'add-to-cart-success-popup'
});
popup.modal('openModal');
Reference for more modal options: https://devdocs.magento.com/guides/v2.4/javascript-dev-guide/widgets/widget_modal.html
copy and paste the catalog-add-to-cart.js
file from vendor\Magento\Catalog\view\frontend\Web\js
to app\design\frontend\[NameSpace]\[Theme]\Magento_Catalog\web\js\catalog-add-to-cart.js
with in that you have to modify ajaxSubmit
function like below.
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);
}
alert("You added Product name to your shopping cart.");
self.enableAddToCartButton(form);
}
});
}
In success
I have added below alert message.
alert("You added Product name to your shopping cart.");
After that fallow below steps.
1) Remove the Magento_Catalog
folder from pub\static\frontend\[NameSpace]\[Theme]\en_US\
2) Run the php bin/magento setup:static-content:deploy --theme NameSpace/Theme
.
3) Open New browser and try to add product to cart above alert message will popup.
Like that you can customize it your way.
-
How can you replace "Product name" with the actual name of the product added?– JasonOct 15, 2017 at 4:31
-