Question

I have added the code for add to cart button but i don't want to refresh the page when i click on button. How to achieve this?

I need the functionality as like default add to cart button(product detail page).

Here is my code:

<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

  $listBlock = $objectManager->get('\Magento\Catalog\Block\Product\ListProduct');

  $addToCartUrl =  $listBlock->getAddToCartUrl($product); ?>

  <form data-role="tocart-form" action="<?php echo $addToCartUrl; ?>" method="post"> 

    <?php echo $block->getBlockHtml('formkey')?>

     <button type="submit" title="Add to Cart" class="action tocart primary">

       <span>Add to Cart</span>
     </button>
 </form>

Any idea?

Thanks

Was it helpful?

Solution

You can just add this script to your phtml.

   <script type="text/x-magento-init">
    {
        "[data-role=tocart-form], .form.map.checkout": {
            "catalogAddToCart": {
                "product_sku": "<?php echo  /* @NoEscape */ 
                        $product->getSku() ?>"
            }
        }
    }
    </script>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top