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.

  • 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 Dec 26 '16 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 Dec 26 '16 at 11:50
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');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.