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>

Any idea?



1 Answer 1


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() ?>"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.