To Pass ajax response from the controller in Magento 2, You need to use Magento\Framework\Controller\Result\JsonFactory Object.
Magento\Framework\Controller\Result\JsonFactory used for sending a response from a controller to ajax request.
Pass your response in setData() method.
<?php 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'; $success = true; return $resultJson->setData([ 'html' => $htmlContent, 'success' => $success ]); }
From Js/Template file which place you have called Ajax Call, You can get Response as html and success parameter from an above response.
You can manage your Response from controller file.