1

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.

2 Answers 2

1

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)
        );
} 
4
  • HI Qaisar, I am getting the following error: "Call to a member function toHtml() on boolean". Can you pls help me with its soln. Commented Jul 12, 2017 at 9:38
  • @ReyaSharma add you layout xml here too so i can see what problem their Commented Jul 12, 2017 at 9:50
  • I have added the script currently in addtocart.phtml and have created a custom module for controller. For now I am not using any layout file. Can you suggest what exactly is gonna be in my layout file? Commented Jul 12, 2017 at 9:58
  • @ReyaSharma updated the code kindly try and feedback Commented Jul 12, 2017 at 10:03
0

You have done some mistake.

1.You should send product id/SKU in your Ajax as Post Parameter

data: {
                customdata1: 'test1',
                customdata2: 'test2',
            },

Should be changes to :

data: {
    customdata1: 'test1',
    customdata2: 'test2',
    sku: '[PRODUCTSKU]'
    }, 

2.You should send product object to your block class from controller using registry as like @Qaisar Satti.

3.The block getBlock('catalog.product.related') only available when Current page is product details and block catalog.product.related define via layout xml. Solution: You should add catalog_product_view handler to your ajax handler

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.