Magento 2.4 - How to enable ajax for add-to-cart button and wishlist button of product widgets on homepage?
-
05-05-2021 - |
Question
I have added products on the homepage using the widget, how to enable ajax for add-to-cart button and wishlist button of product widgets.
La solution
To enable AJAX add to cart on home page, You need to add small JS code
create:
app/design/frontend/{Package}/{theme}/Magento_Theme/layout/cms_index_index.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Magento\Framework\View\Element\Template" name="myaddto" template="Magento_Theme::myaddto.phtml"/>
</referenceContainer>
</body>
</page>
create:
app/design/frontend/{Package}/{theme}/Magento_Theme/templates/myaddto.phtml
<script type="text/x-magento-init">
{
"[data-role=tocart-form]": {
"catalogAddToCart": {}
}
}
</script>
Note: If you have any other custom phtml on home page, you can add above in that file as well!
Autres conseils
You have to override addtocart.phtml file
app/design/frontend/vendorname/themename/Magento_Catalog/templates/product/view/addtocart.phtml
Now Just Replace "bindSubmit": false to "bindSubmit": true
<script type="text/x-magento-init">
{
"#product_addtocart_form": {
"catalogAddToCart": {
"bindSubmit": false
}
}
}
</script>
To
<script type="text/x-magento-init">
{
"#product_addtocart_form": {
"catalogAddToCart": {
"bindSubmit": true
}
}
}
</script>
Now delete cache and page_cache folder or flush cache.
Note: Make sure you have to set No from Store->Configuration->Sales->Checkout->Shopping Cart->After Adding a Product Redirect to Shopping Cart to No