How to return a JSON response from a controller in Magento 2

Posted in Magento 2 By BrainActs

Apr 5, 2018, 5:39:46 PM
How to return a JSON response from a controller in Magento 2

During creation extensions for Magento2, the developer often needs to return the data from the controller in the JSON format. Usually, it is REST / API requests that only need data (list of products, customers, customs data etc.).

There is a base class in Magento 2 that implements the return of data in the JSON format. In order to use it, you need to create an object of this class the controller where the return data is planned and transfer data to it as an array. Then this object needs to be returned as a result of the controller's work.

  1. Add a property to the controller class
    
    /**
    * @var \Magento\Framework\Controller\Result\JsonFactory
    */
    protected $resultJsonFactory;
                
                
  2. Add an input parameter to the constructor
    
    \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
                
                
    Assign it to the newly created property
    
    $this->resultJsonFactory = $resultJsonFactory;
                
                
  3. Create an object from the factory in the controller's execute method
    
    /** @var \Magento\Framework\Controller\Result\Json $resultJson */
    $resultJson = $this->resultJsonFactory->create();
                    
                
  4. Prepare the data and transfer it to the new object $resultJson
    
    $response = ['success' => 'true'];
    $resultJson->setData($response);
                    
                
  5. Return result
    
    return $resultJson;
                    
                
Code example Magento\Backend\Controller\Adminhtml\Ajax\Translate:
        

namespace Magento\Backend\Controller\Adminhtml\Ajax;

use Magento\Backend\App\Action;

class Translate extends \Magento\Backend\App\Action
{
    /**
     * @var \Magento\Framework\Translate\Inline\ParserInterface
     */
    protected $inlineParser;

    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * Authorization level of a basic admin session
     */
    const ADMIN_RESOURCE = 'Magento_Backend::content_translation';

    /**
     * @param Action\Context $context
     * @param \Magento\Framework\Translate\Inline\ParserInterface $inlineParser
     * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
     */
    public function __construct(
        Action\Context $context,
        \Magento\Framework\Translate\Inline\ParserInterface $inlineParser,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
    ) {
        parent::__construct($context);
        $this->resultJsonFactory = $resultJsonFactory;
        $this->inlineParser = $inlineParser;
    }

    /**
     * Ajax action for inline translation
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $translate = (array)$this->getRequest()->getPost('translate');

        /** @var \Magento\Framework\Controller\Result\Json $resultJson */
        $resultJson = $this->resultJsonFactory->create();
        try {
            $this->inlineParser->processAjaxPost($translate);
            $response = ['success' => 'true'];
        } catch (\Exception $e) {
            $response = ['error' => 'true', 'message' => $e->getMessage()];
        }

        $this->_actionFlag->set('', self::FLAG_NO_POST_DISPATCH, true);
        return $resultJson->setData($response);
    }
}