Back to Top

Return JSON Data with AJAX call in Magento 2

Updated 6 April 2023

Magento 2 Ajax call Request – In this dev blog, we will see how to return JSON data from the controller while doing an Ajax call.
The situation may come that you are doing some customization and need to deal will JSON data from the controller then here is the way how we can go about it.

For that, we can use the Magento core class,

Magento\Framework\Controller\ResultFactory

which has list of constant mapped to corresponding classes :

self::TYPE_JSON => 'Magento\Framework\Controller\Result\Json',
self::TYPE_RAW => 'Magento\Framework\Controller\Result\Raw',
self::TYPE_REDIRECT => 'Magento\Framework\Controller\Result\Redirect',
self::TYPE_FORWARD => 'Magento\Framework\Controller\Result\Forward',
self::TYPE_LAYOUT => 'Magento\Framework\View\Result\Layout',
self::TYPE_PAGE => 'Magento\Framework\View\Result\Page'

among these, we can use the constant to return json data :

const TYPE_JSON = 'json'

Now here is the complete code to implement above.

Searching for an experienced
Magento 2 Company ?
Find out More
<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_<modulename>
 * @author    Webkul Software Private Limited
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Webkul\<modulename>\Controller\Attachment;

use Magento\Framework\Controller\ResultFactory;

class <action> extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\App\Action\Contex
     */
    private $context;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context
    ) {
        parent::__construct($context);
        $this->context           = $context;
    }
	
    /**
     * @return json
     */
    public function execute()
    {
        $whoteData = $this->context->getRequest()->getParams();
        $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        $resultJson->setData(["message" => ("Invalid Data"), "suceess" => true]);
        return $resultJson;
    }
}

This is all we need , hope this help you out. happy coding.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home