Today topic Magento 2 jquery ajax request. sometime we need to load data with loading the page so for that we need ajax to load data. So today we focus how to use jquery ajax request in magento 2. Magneto have already added the jquery library.you can inject it with require. Here is example of using of jqery ajax for getting the json response from controller.
<script>
require(['jquery', 'jquery/ui'], function($){
$.ajax({
method: "POST",
url: "<?php echo $block->getUrl('helloworld/ajax/index'); ?>",
data: { q: "test"},
dataType: "json"
})
.done(function( msg ) {
//do something with you return data
});
});
require(['jquery', 'jquery/ui'], function($){
$.ajax({
method: "POST",
url: "<?php echo $block->getUrl('helloworld/ajax/index'); ?>",
data: { q: "test"},
dataType: "json"
})
.done(function( msg ) {
//do something with you return data
});
});
you we use controller ResultFactory to get back json response.
<?php
namespace QaisarSatti\HelloWorld\Controller\Ajax;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
class Index extends Action {
protected $request;
public function __construct(Context $context,array $data = [])
{
parent::__construct($context,$data);
}
public function execute() {
$data=array("bdfb");
$resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
$resultJson->setData($data);
return $resultJson;
}
}
namespace QaisarSatti\HelloWorld\Controller\Ajax;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
class Index extends Action {
protected $request;
public function __construct(Context $context,array $data = [])
{
parent::__construct($context,$data);
}
public function execute() {
$data=array("bdfb");
$resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
$resultJson->setData($data);
return $resultJson;
}
}