4

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.

Amit Bera
77.8k21 gold badges127 silver badges240 bronze badges
asked Dec 26, 2016 at 11:34
2
  • 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'); Commented 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. Commented Dec 26, 2016 at 11:50

1 Answer 1

7

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');

answered Dec 26, 2016 at 12:06

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.