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.
- 
 where you have written your ajax code . is it in form ? post the code . also if you want to pass your controller in ajax url parameter you can pass it like $this->getUrl('path to controller');Manthan Dave– Manthan Dave2016年12月26日 11:43:21 +00:00Commented Dec 26, 2016 at 11:43
- 
 I am trying to write Ajax call in web/J's/myjavascript.js.. in admin panel there is one form.that form has the select menu.i have to fetch the collection as per menu selected by user.so what my plane is to call the controller using Ajax ..and fetch that data.vijay b– vijay b2016年12月26日 11:50:50 +00:00Commented Dec 26, 2016 at 11:50
1 Answer 1
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');