Magento 2 AJAX – Create Block Over AJAX in Magento 2

ajaxblockscontrollersjsonmagento2

I want to send block html in JSON response.

To be specific – I want to add functionality where customers are able to edit their addresses via Ajax requests. So the block class will be \Magento\Customer\Block\Address\Edit instance.

In Magento 1.x it will be just something like that:
$this->getLayout()->createBlock('xxx')->toHtml()

How to achieve similar things in Magento 2 ?

Am I doing it in proper way? Or maybe Magento 2 implements other ways of doing such things?

Best Answer

-- \Magento\Framework\View\LayoutFactory to create the block.
-- \Magento\Framework\Controller\Result\RawFactory to return Json format.

/**
  * @var \Magento\Framework\View\LayoutFactory
  */
protected $layoutFactory;


/**
  * @var \Magento\Framework\Controller\Result\RawFactory
 */
protected $resultRawFactory;

public function __construct(
    \Magento\Framework\App\Action\Context;
    \Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
    \Magento\Framework\View\LayoutFactory $layoutFactory
    .....
) {

      $this->resultRawFactory = $resultRawFactory; 
      $this->layoutFactory = $layoutFactory;
      parent::__construct($context);

}

public function execute() {

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

$block = $layout->getLayout()
                ->createBlock('\Magento\Customer\Block\Address\Edit')
                ->setTemplate('Magento_Customer::address/edit.phtml')
                ->toHtml();

/** @var \Magento\Framework\Controller\Result\Raw $resultRaw */

$resultRaw = $this->resultRawFactory->create();
$resultRaw->setContents($block);

//$this->getResponse()->setBody($block); <= We also can use setBody.

return $resultRaw;

}