I am not able to find correct approaches to done this work. I found some resources but there they guys are using model files also but they didn't explain about that files. My codes are below
Controller file
namespace Vendor\Modulename\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Controller\ResultFactory;
class Index extends Action
{
/**
* @var \Tutorial\SimpleNews\Model\NewsFactory
*/
protected $resultJsonFactory;
protected $resultPageFactory;
/**
* @param Context $context
* @param NewsFactory $modelNewsFactory
*/
public function __construct(
Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
$this->resultJsonFactory = $resultJsonFactory;
parent::__construct($context);
}
public function execute() {
$result = $this->resultJsonFactory->create();
if ($this->getRequest()->isAjax()))
{
$test=Array
(
'Firstname' => 'What is your firstname',
'Email' => 'What is your emailId',
'Lastname' => 'What is your lastname',
'Country' => 'Your Country'
);
return $result->setData($test);
}
}
}
Template file
data = jQuery(this).serialize();
jQuery.ajax({
showLoader: true,
type: "POST",
dataType: "json",
contentType: "application/json",
url: "modulename/index/index",
data: "label=" + abc,
success: function (result) { jQuery('#result').html(result); },
error: function (error) { alert(error); }
Please somebody guide me