How to trigger add to cart function After loading product by Ajax call.
this above product loaded by ajax call I have to found solution if I click add to cart button, then add to cart function triggered. Kindly help me to find solution
1st step: in phtml where product is displaying
$addToCartUrl = $block->getAddToCartUrl($products);
Here $products is object of a \Magento\Catalog\Model\ProductFactory class.
$this->product->create()->load($productId);
2nd step: In Block paste
public function getAddToCartUrl($product) { return $this->listProductBlock->getAddToCartUrl($product); }
Where listProductBlock is object of
Magento\Catalog\Block\Product\ListProduct
Class
3rd Step: in phtml again paste this code for "Add To Cart" button
<form data-role="tocart-form" action="<?php echo $addToCartUrl; ?>" method="post">
<?php echo $block->getBlockHtml('formkey')?>
<div class="btn">
<button type="submit" title="Add to Cart" class="action tocart primary">
<span>Add to Cart</span>
</button>
</div>
</form>
Step 4: In etc/frontend/sections.xml:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
Please let me know if you face any problem.
Try this
$(document).ajaxComplete(function (event, xhr, settings) {
if (settings.url.indexOf("customer/section/load/?sections=cart") > 0) {
alert("product added in basket")
}
});