I have to call the controller using Ajax in Admin backend of Magento 2. Can we directly call the controller or do we have to include any key values?
Please help me.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityI have to call the controller using Ajax in Admin backend of Magento 2. Can we directly call the controller or do we have to include any key values?
Please help me.
Our Ajax response should return the key values. We can create an Admin controller like:
app/code/Vendor/Module/Controller/Adminhtml/CustomAjax/Index.php
<?php
namespace Vendor\Module\Controller\Adminhtml\CustomAjax;
class Index extends \Magento\Backend\App\Action
{
/**
* @var \Magento\Framework\Controller\Result\JsonFactory
*/
protected $resultJsonFactory;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
)
{
parent::__construct($context);
$this->resultFactory = $resultJsonFactory;
}
public function execute()
{
$params = $this->getRequest()->getParams();
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData([
'messages' => 'Successfully. Params: ' . json_encode($params),
'error' => false
]);
}
}
Remember to declare the route:
app/code/Vendor/Module/etc/adminhtml/routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="vendor" frontName="vendor">
<module name="Vendor_Module"/>
</route>
</router>
</config>
In your block, we can call the url: $this->getUrl('vendor/customAjax')
;