0

How to trigger add to cart function After loading product by Ajax call.

enter image description here

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

2 Answers 2

0

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.

4
  • Thank you for providing me solution but it not work for me, because after adding product to cart it response JSON file. Commented Feb 7, 2022 at 3:54
  • Can you please explain more, also please see my updated answer.
    – Ankit
    Commented Feb 7, 2022 at 4:20
  • i am saying that when i click add to cart button than browser show JSON output on the screen while product add to cart successfully. i want this output not show by screen. Commented Feb 7, 2022 at 4:30
  • I gave the answer you asked about add to cart functionality, if it is working please accept as a answer. Also, for your next question can you please create another query with more details so I can look into it.
    – Ankit
    Commented Feb 7, 2022 at 6:32
0

Try this

$(document).ajaxComplete(function (event, xhr, settings) {
    if (settings.url.indexOf("customer/section/load/?sections=cart") > 0) {
       alert("product added in basket")
    }  
});

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.