To pass Ajax response from the controller in Magento 2, You need to use Magento\Framework\Controller\Result\JsonFactory Object.
Many times your custom functionality requires you to use Ajax request on a page to display information without any page load and in this situation, you need to know about Ajax use in Magento 2 to achieve your requirement.
Magento\Framework\Controller\Result\JsonFactory is used for sending a response from a controller to an Ajax request.
Pass your response in the setData() method.
<?php declare(strict_types=1); namespace Rbj\AjaxResponse\Controller\Index; class AjaxResponse extends \Magento\Framework\App\Action\Action { public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory ) { parent::__construct($context); $this->resultJsonFactory = $resultJsonFactory; } public function execute() { $resultJson = $this->resultJsonFactory->create(); $htmlContent = 'Pass Html Content'; return $resultJson->setData([ 'html' => $htmlContent, 'success' => true ]); } }
From the JS/Template file which you have called Ajax Call, You can get Response as html and success parameter from the above response.
You can manage your Response from the controller file.