3

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.

3

5 Answers 5

11

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.

3
  • I want to add Upsell Product add to cart using ajax. so what should i do for that ? Nov 27, 2017 at 7:37
  • NIce its working fine. Nov 2, 2018 at 10:10
  • Do we need to add this code in list.phtml or addtocart.phtml? Dec 1, 2018 at 11:29
0

You could look to target the on click with jQuery / Prototype and prevent the default action then submit the form and simply add a message indicating it has been successful.

jQuery(document).on('click', '#product_addtocart_form button', function(e) { e.preventDefault(); /* submit form and process result */ });
1
  • where we need to add this line..explain clearly Dec 11, 2018 at 14:00
0

Try this


<form id="product_addtocart_form" data-name = "'.$product->getName().'" data-role="tocart-form" action="'.$postParams['action'].'" method="post">
    <input type="hidden" name="product" value="'.$postParams['data']['product'].'">
    <input type="hidden" name="' . Action::PARAM_NAME_URL_ENCODED .'" value="' . $postParams['data'][Action::PARAM_NAME_URL_ENCODED] .'">' . $this->getBlockHtml('formkey') .'
    <button type="submit" title="' . __('Add to cart') . '" class="action tocart primary">
            <span>' . __('Add to cart') . '</span>
    </button>
</form>
<script type="text/x-magento-init">
{
    "[data-role=tocart-form], .form.map.checkout": {
        "catalogAddToCart": {
            "bindSubmit": true
         }
     }
}
</script>
0

Add method to your class

public function __construct(
    ......................................................
    \Magento\Catalog\Model\ProductFactory $productFactory,
    \Magento\Catalog\Block\Product\ListProduct $listProductBlock,
    ......................................................
) {
    ......................................................
    $this->productFactory = $productFactory;
    $this->listProductBlock = $listProductBlock;
    ......................................................
}

public function getProductData($id)
{
    $collection = $this->productFactory->create()->load($id);
    return $collection;
}

public function getAddToCartPostParams($product)
{
    return $this->listProductBlock->getAddToCartPostParams($product);
}

Add into your phtml file

<?php
$_product = $block->getProductData(11);
?>
<?php $postParams = $block->getAddToCartPostParams($_product); ?>
<form data-role="tocart-form" action="<?php /* @escapeNotVerified */ echo $postParams['action']; ?>" method="post">
    <input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $postParams['data']['product']; ?>">
    <input type="hidden" name="<?php /* @escapeNotVerified */ echo "uenc"; ?>" value="<?php /* @escapeNotVerified */ echo $postParams['data']['uenc']; ?>">
    <?php echo $block->getBlockHtml('formkey')?>
    <button type="submit"
            title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
            class="action tocart primary">
        <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
    </button>
</form>
<script type="text/x-magento-init">
    {
        "[data-role=tocart-form]": {
            "Magento_Catalog/js/validate-product": {
                "bindSubmit": true
            }
        }
    }
</script>
0

Please add the below code at last in your phtml file and then check after cache flush.

<?php if (!$block->isRedirectToCartEnabled()) : ?>
    <script type="text/x-magento-init">
        {
            "[data-role=tocart-form], .form.map.checkout": {
                "catalogAddToCart": {
                    "product_sku": "<?= $block->escapeJs($_product->getSku()) ?>"
                }
            }
        }
    </script>
<?php endif; ?>

Note: Make sure you have to set the No option from admin which steps i have given below.

Admin -> Stores -> Configuration -> Sales -> Checkout -> Shopping Cart -> After Adding a Product Redirect to Shopping Cart to No

Your Answer

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

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