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);
}
});
});