Back to Top

Render an HTML Using an Ajax Call and creating HTML from the block in the controller file programmatically in Magento 2 Module

Updated 23 February 2024

Magento 2 provides a Magento\Framework\Controller\Result\JsonFactory  a class that can be used to return a JSON response from a controller. We will use the factory method of this class to return our HTML in JSON format.

Create PHTML File

file index.phtml under app/code/Webkul/AjaxCall/view/frontend/templates from where we want to initialize our ajax call.

<?php
    $url = $block->getUrl('ajaxcall/index/ajaxcontroller');
?>
<div id="bodyContentMain">
</div>
<script type="text/javascript">
    require(['jquery'], function($){
        $(document).ready(function() {
            setTimeout(function(){
                $.ajax({
                    context: '#bodyContentMain',
                    url: '<?= $url ?>',
                    type: "POST",
                    data: {'newText':'Hello Everyone'},
                }).done(function (data) {
                    $('#bodyContentMain').html(data.result);
                    return true;
                });
            },2000);
        });
    });
</script>

You can call this file by creating a separate controller and layout because ajax will run after this file is loaded. I am not covering here the creation of the controller and layout to load any phtml file.

Searching for an experienced
Magento 2 Company ?
Find out More

You can go through the given below webkul blog for this

https://webkul.com/blog/create-hello-module-in-magento2/

In this file, we have created one blank div with id #bodyContentMain. Using ajax call we will call the controller file and return an HTML. Using JQUERY we will fill that HTML into div.

In javascript code, in the ajax function, we are passing two parameters. First is AjaxUrl which is the URL of the controller (in our case it is ajaxcall/index/ajaxcontroller/, a “ajaxcall” is the front name of our module and ajaxcontroller.php is our controller file) from where we will return a JSON response, the second is the hardcoded text “Hello Everyone”. You can pass any other parameters in this call like product id. For demonstration purposes, we have passed hardcoded text parameters.

And in the done method, we are filling the div content using data.result, which contains the actual HTML.

Create Controller File

Create a controller file AjaxController.php under app/code/Webkul/AjaxCall/Controller/Index directory and write the below code

<?php
/**
 * Webkul Software
 *
 * @category    Webkul
 * @package     Webkul_AjaxCall
 * @author      Webkul
 * @copyright   Copyright (c)  Webkul Software Private Limited (https://webkul.com)
 * @license     https://store.webkul.com/license.html
 */
namespace Webkul\AjaxCall\Controller\Index;
 
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\View\Result\PageFactory;
 
class AjaxController extends Action
{
 
    /**
     * @var PageFactory
     */
    protected $_resultPageFactory;
 
    /**
     * @var JsonFactory
     */
    protected $_resultJsonFactory;
 
    /**
     * View constructor.
     * @param Context $context
     * @param PageFactory $resultPageFactory
     * @param JsonFactory $resultJsonFactory
     */
    public function __construct(    
        Context $context, 
        PageFactory $resultPageFactory, 
        JsonFactory $resultJsonFactory,
        \Webkul\PathologyLab\Helper\Data $helper
    )
    {
        $this->_resultPageFactory = $resultPageFactory;
        $this->helper = $helper;
        $this->_resultJsonFactory = $resultJsonFactory;
        parent::__construct($context);
    }
 
    /**
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->_resultJsonFactory->create();
        $resultPage = $this->_resultPageFactory->create();
        $text = $this->getRequest()->getParam('newText');
        $block = $resultPage->getLayout()
                ->createBlock('Webkul\AjaxCall\Block\Index\AjaxView')
                ->setTemplate('Webkul_AjaxCall::ajaxview.phtml')
                ->setData('data',$text)
                ->toHtml();
        $result->setData(['result' => $block]);
        return $result;
    }
}

we have passed the block file and template file in which we will write our business logic and HTML code respectively. We have passed the hardcoded text variable in the setData method so that it is available in the block file for any business logic. we are setting our data in the setData method which is preparing JSON output.

Create Block File

Create AjaxView.php under app/code/Webkul/AjaxCall/Block/Index directory and write the below code

<?php
/**
 * Webkul Software
 *
 * @category    Webkul
 * @package     Webkul_AjaxCall
 * @author      Webkul
 * @copyright   Copyright (c)  Webkul Software Private Limited (https://webkul.com)
 * @license     https://store.webkul.com/license.html
 */
namespace Webkul\AjaxCall\Block\Index;

use Magento\Framework\View\Element\Template;
 
class AjaxView extends Template
{
    public function __construct(  
      Template\Context $context, 
      array $data = []
    )
    {
        parent::__construct($context, $data);
    }
 
    protected function _prepareLayout()
    {
        return parent::_prepareLayout();
    }

    /* you can create any function and write business logic here and */
}

Create Template File

Create ajaxview.phtml file under app/code/Webkul/AjaxCall/view/frontend/templates directory with your HTML code.

<?php
$data = $block->getData();
?>
<div>
  <div><?= $data['data'] ?></div>
</div>

You can see here data is available in our template file. We have used a string here just for demonstration but you can pass and use another thing like product id and write or fetch any business logic from the block file and render an HTML code in our template file.

Result
Result

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home