1

How to create block from controller by ajax method?

    $result = $this->resultJsonFactory->create();
    $resultPage = $this->_resultPageFactory->create();
    $block = $resultPage->getLayout()
        ->createBlock('Module\Ajaxcart\Block\BuildProductInfo')
        ->setTemplate('Module_Ajaxcart::buildproductinfo.phtml')
        ->toHtml();

Showing Cache Exception Error

1
  • Please share your full code of execute() function
    – Amit Bera
    May 28, 2019 at 12:18

2 Answers 2

2

Try This :-

protected $resultPageFactory;

public function __construct(
    Magento\Framework\View\Result\PageFactory $resultPageFactory
){
      $this->resultPageFactory = $resultPageFactory;
} 
public function execute() 
{

     $layout = $this->resultPageFactory->create();

     $block = $layout->getLayout()
                    ->createBlock('Module\Ajaxcart\Block\BuildProductInfo')
                    ->setTemplate('Module_Ajaxcart::buildproductinfo.phtml')
                    ->toHtml();
}
12
1

You don't send a response from your ajax controller.

result factory type should be json

$resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);

Code Sample:

<?php
namespace Magento\Contact\Controller\Index;

use Magento\Framework\Controller\ResultFactory;

class AjaxCall extends \Magento\Framework\App\Action\Action
{
    public function __construct(
       \Magento\Framework\App\Action\Context $context
    ) {
        parent::__construct($context);
    }
    public function execute() {
        $this->_view->loadLayout();
        $layout = $this->_view->getLayout();
        $customBlock = $layout->createBlock(
            \Magento\Contact\Block\ContactForm::class,
            'ajax.contact-us',
            ['data' => ['id' => 'test']]
        )->setTemplate('Magento_Contact::form.phtml');

        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        return $resultJson->setData(
                [
                    'html' => $customBlock->toHtml(),
                    'message' => __('my message')
                ]
            );
    }

}
4
  • Source class "\Module\Ajaxcart\Controller\Cart\Result" for "Module\Ajaxcart\Controller\Cart\ResultFactory" generation does not exist. May 28, 2019 at 12:49
  • Please share your code and some issue at depency injection
    – Amit Bera
    May 28, 2019 at 12:50
  • Can you share chat box May 28, 2019 at 12:51
  • Post your full code controller at chat room chat.stackexchange.com/rooms/94208/…
    – Amit Bera
    May 28, 2019 at 13:01

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.