Load Related Products of Simple Product Using AJAX – Magento 2.1

magento-2.1related-products

I have a configurable product and on selection of its simple product I need its respective related products loaded via ajax. Any help will be highly appreciated.

This is how I call my ajax:

<script type="text/javascript">
require(["jquery"],function($) {
    $(document).ready(function() {
        var customurl = "<?php echo $this->getUrl().'custom/custom/index'?>";
        $.ajax({
            url: customurl,
            type: 'POST',
            dataType: 'json',
            data: {
                customdata1: 'test1',
                customdata2: 'test2',
            },
        complete: function(response) {

        },
            error: function (xhr, status, errorThrown) {
                console.log('Error happens. Try again.');
            }
        });
    });
});

And my controller file execute method looks something like this:

public function execute()
{        
    $resultRedirect = $this->pageFactory->create();          
        $blockInstance = $resultRedirect->getLayout()->getBlock('catalog.product.related');
        $message['html'] = $blockInstance->toHtml();

        /** Json Responce */
        $this->getResponse()->representJson(
            $this->jsonData->jsonEncode($message)
        );
}  

However I am not able to fetch the products using ajax and also I need to know how I go about with specific simple product.

Best Answer

You need to set the product registry to get the current related product.

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Catalog\Model\ProductFactory $_productloader,
    \Magento\Framework\Registry $registry)
{
    $this->registry = $registry;
    $this->_productloader = $_productloader;

}    




public function execute()
{
    $id=1; //pass current product id here        
    $product = $this->_productloader->create()->load($id);
    $this->registry->register('product', $product);
    $resultRedirect = $this->pageFactory->create();          

       $message['html']=$resultRedirect->getLayout()
                 ->createBlock("Magento\Catalog\Block\Product\ProductList\Related")
                 ->setTemplate("Magento_Catalog::product/list/items.phtml")
                 ->setData('type', 'related')
                 ->toHtml();


        /** Json Responce */
        $this->getResponse()->representJson(
            $this->jsonData->jsonEncode($message)
        );
} 
Related Topic