10

I have loaded products collection using ajax. My controller URL is something like this:

www.example.com/whoboughtthisproduct/index/getproducts

Now products are loading properly, but when user click on add to cart button instead of add product to cart it is redirecting user to www.example.com/whoboughtthisproduct/index/getproducts

My controller code is this:

protected $resultPageFactory;

public function __construct(
    Context $context,
    \Magento\Framework\View\Result\PageFactory $resultPageFactory
)
{
    $this->resultPageFactory = $resultPageFactory;
    parent::__construct($context);
}


public function execute()
{
    $viewBlock = $this->resultPageFactory->create();
    $block = $viewBlock->getLayout()
        ->createBlock('Vendor\WhoBoughtThisProduct\Block\ProductList')
        ->setTemplate('Magento_Catalog::product/list.phtml')
        ->toHtml();

    //Setting response
    $this->getResponse()->setBody($block);
}

And the code where I am calling ajax is this:

require([
    'jquery'
], function($){
    jQuery.ajax({
        url: "/whoboughtthisproduct/index/getproducts",
        type: "POST",
        data: "prod=<?php echo $productId; ?>",
        success: function (res) {
            if(res.indexOf("find products matching the selection") > -1){
                //if no products found then do nothing
                return;
            }

            var result = jQuery('.product-items', res).html();
            jQuery(".bought-slider").html(result);
        }
    });
});
7

I found the solution of this one few times ago but forgot to post it. I just add this line in my ajax request success case jQuery( "form[data-role='tocart-form']" ).catalogAddToCart();

require([
    'jquery'
], function($){
    jQuery.ajax({
        url: "/whoboughtthisproduct/index/getproducts",
        type: "POST",
        data: "prod=<?php echo $productId; ?>",
        success: function (res) {
            if(res.indexOf("find products matching the selection") > -1){
                //if no products found then do nothing
                return;
            }

            var result = jQuery('.product-items', res).html();
            jQuery(".bought-slider").html(result);
            jQuery( "form[data-role='tocart-form']" ).catalogAddToCart();
        }
    });
});

I hope it help others who is facing the same kind of problem.

1
  • mmmm, not sure about this... catalogAddToCart() as a jQuery function? – Raul Sanchez Aug 27 '20 at 9:20

Your Answer

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

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