When writing custom code for Magento, if there is data involved, more often than not, a controller needs to be created. The controller handles the request and returns an appropriate response. The response could be several different things, but if the request is an ajax request, then we can be pretty certain that the response returned is most often in the JSON format.

So how do we return response from the controller in a specific format?

When I initially started developing for Magento 2, I thought returning an array would suffice and Magento will take care of the rest. But I was wrong. Although Magento 2 can handle several different types of requests, they need to be returned in a certain way for the controller to send the response in the format needed.

To return result in any particular format Magento controller requires to return an object of Magento\Framework\Controller\ResultInterface. This is handles all the necessary aspects of returning the correct response by setting the headers, body etc.

You can either use one of the existing classes for returning a particular response, or create your own class that implements Magento\Framework\Controller\ResultInterface or extends Magento\Framework\Controller\AbstractResult (if you don’t want to code the complete implementation).

How do we return JSON respose from our controller?

To return a JSON response from your controller, you create an object of Magento\Framework\Controller\Result\Json using Magento\Framework\Controller\Result\JsonFactory.

To do this, in your controller, inject Magento\Framework\Controller\Result\JsonFactory in the constructor (__construct method) and the create an object of Magento\Framework\Controller\Result\Json using $this->resultJsonFactory->create() as follows :

<?php
namespace {Vendor}\{YourModuleName}\Controller\Adminhtml\Guest;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Controller\Result\JsonFactory;

class {YourController} extends Action
{
    /**
     * @var JsonFactory
     */
    private $resultJsonFactory;

    ...

    /**
     * @param Context     $context
     * @param JsonFactory $resultJsonFactory
     */
    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory,
        ...
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        ...

        parent::__construct($context);
    }

    /**
     * @return ResultInterface
     */
    public function execute()
    {
        $resultJson = $this->resultJsonFactory->create();
        return $resultJson->setData([
            'success' => true,
            'message' => __('Your message here'),
            ...
        ]);
    }
}
Live chat: cookie consent required

Copyright © Hungersoft 2019

· Terms & Conditions · Privacy policy