Magento 2 – AJAX Add to Cart

addtocartmagento2

I have the above code on the homepage and this form adds the product to the cart. However, unlike the same form on the product listing page, it does this through a page refresh instead of asynchronously. How can I prevent this page refresh?

<form action="/checkout/cart/add/uenc/[key]/product/1/" method="post" id="product_addtocart_form">

<input type="hidden" name="product" value="1" tabindex="0">
<input name="form_key" type="hidden" value="[form_key]" tabindex="0">
<button class="action tocart primary" type="submit" title="Add to Cart" tabindex="0">
<span>Add to Cart</span>
</button>

</form>

There seem to be various script blocks that affect the add to cart form but

I have tried inserting these with no effect.

Best Answer

In product listing page, Magento has a jQuery widget to handle the Ajax Add To Cart. We should take a look:

vendor/magento/module-catalog/view/frontend/templates/product/list.phtml

 <script type="text/x-magento-init">
        {
            "[data-role=tocart-form], .form.map.checkout": {
                "catalogAddToCart": {
                   "bindSubmit": true
                 }
            }
        }
 </script>

You can try with this script also.

In your form, it should has data-role=tocart-form.

Related Topic