Magento 2 – How to Dynamically Create Block and Send as AJAX Call Response

ajaxcontrollersdynamicmagento2response

I want replacement of following in magento 2.x

$block = $this->getLayout()->createBlock('customer/form_login')->setTemplate('persistent/customer/form/login.phtml');

$this->getResponse()->setBody($block->toHtml());

Best Answer

You can try following way to create new block inside controller

<?php

namespace [Vendor]\[Module]\Controller\[ControllerName];

use Magento\Framework\App\Action\Context;

class [YourControllerAction] extends \Magento\Framework\App\Action\Action
{

    /**
     * Index constructor.
     *
     * @param Context $context
     */
    public function __construct(
        Context $context
    ) {
        parent::__construct($context);
    }

    /**
     * @return 
     */
    public function execute()
    {
        $block = $this->_view->getLayout()
                ->createBlock('Magento\Customer\Block\Form\Login')
                ->setTemplate('Magento_Customer::form/login.phtml')
                ->toHtml();

        $this->getResponse()->setBody($block);
    }
}
Related Topic