1

In Magento 2 the normal Add to Cart button has a very nice AJAX-based logic to add products to the cart. However, when we use a Catalog Products List widget for example in CMS pages in the Home Page the button in this products list works with an HTTP POST which reloads the current page. I want to add Ajax add to cart in grid.phtml in home page(Widget).

User experience suffers from this and it would be desirable if the button would have the same AJAX logic like in the default category product lists or on product pages.

4

You have to override new_grid.phtml file

app/design/frontend/vendorname/themename/Magento_Catalog/templates/product/widget/new/content/new_grid.phtml

Now Just Add

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

And write your Add to Cart button under the form.Just Replace form

<?php 
$postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
$postData = $postDataHelper->getPostData($block->getAddToCartUrl($_item), ['product' => $_item->getEntityId()])
?>
<button class="action tocart primary" data-post='<?= /* @escapeNotVerified */ $postData ?>' type="button" title="<?= /* @escapeNotVerified */ __('Add to Cart') ?>">
    <span><?= /* @escapeNotVerified */ __('Add to Cart') ?></span>
</button>

To

<?php
$postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
$postData = $postDataHelper->getPostData($block->getAddToCartUrl($_item), ['product' => $_item->getEntityId()]);
$widgetdata = json_decode($postData);
//var_dump($mydata->action);
?>
<form data-role="tocart-form" data-product-sku="<?= /* @NoEscape */ $_item->getSku() ?>" action="<?= /* @NoEscape */ $widgetdata->action ?>" method="post">
   <input type="hidden" name="product" value="<?= /* @escapeNotVerified */ $widgetdata->data->product ?>">
   <!--<input type="hidden" name="<? //= /* @escapeNotVerified */ Action::PARAM_NAME_URL_ENCODED   ?>" value="<? //= /* @escapeNotVerified */ $postParams['data'][Action::PARAM_NAME_URL_ENCODED]   ?>">-->
  <?= $block->getBlockHtml('formkey') ?>
  <button type="submit" title="<?= $block->escapeHtml(__('Add to Cart')) ?>" class="action tocart primary">
      <span><?= /* @escapeNotVerified */ __('Add to Cart') ?></span>
  </button>
</form>
1
  • Thank Ashna. this active is on ver 2.3. – River Jan 28 at 3:50
0

I Found this free extension from Tigren that adds ajax support to add to cart button in widgets , here is the link to it link to free extension

note: if you don't like the popup you can disable it from the admin dashboard

hope this will help someone in need

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy