Magento 2: Add to cart button issue on phtml file (Ajax base add to cart Prodcut )

magento.stackexchange https://magento.stackexchange.com/questions/304767

  •  09-04-2021
  •  | 
  •  

Вопрос

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

Это было полезно?

Решение

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>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с magento.stackexchange
scroll top