Retreive and return response from controller in magento2
ajax
<script>
require(['jquery', 'jquery/ui'], function($){
$.ajax({
method: "POST",
url: "<?php echo $block->getUrl('modulanefrontname/ajax/search'); ?>",
data: { q: 'some' },
dataType: "json"
})
.done(function( msg ) {
/do your thing
});
});
you can use ResultFactory
controller
<?php
namespace MyNameSpace\MyModule\Controller\Index;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
class Custom extends Action {
protected $request;
public function __construct(Context $context,array $data = []) {
parent::__construct($context,$data);
}
public function __execute() {
if ($this->getRequest()->getPost('q')):
$query=$this->getRequest()->getPost('q');
$data=array("bdfb");
$resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
$resultJson->setData($data);
return $resultJson;
endif;
}
}
Try with below code in controller,
<?php
namespace Vendor\Modulename\Controller\Index;
use Magento\Framework\Controller\ResultFactory;
class Custom extends \Magento\Framework\App\Action\Action
{
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Json\Helper\Data $jsonHelper,
\Magento\Framework\View\Result\PageFactory $resultFactory
) {
$this->jsonHelper = $jsonHelper;
$this->resultFactory = $resultFactory;
parent::__construct($context);
}
public function execute()
{
/** @var \Magento\Framework\View\Result\Page $resultPage */
$resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
/** @var \Magento\Framework\Controller\Result\Raw $response */
$response = $this->resultFactory->create(ResultFactory::TYPE_RAW);
$response->setHeader('Content-type', 'text/plain');
$data1 = 'This is test';
$data2 = 20;
$response->setContents(
$this->jsonHelper->jsonEncode(
[
'data1' => $data1,
'data2' => $data2,
]
)
);
return $response;
}
}
Inside jquery,
jQuery.ajax({
url: "/modulename/index/custom",
type: 'POST',
dataType: 'json',
data: {},
complete: function(response) {
stores = response.responseJSON.data1;
selectedStore = response.responseJSON.data2;
console.log(data1+' '+data2);
},
error: function (xhr, status, errorThrown) {
console.log('Error happens. Try again.');
}
}); // ajax function end here