{"id":1415,"date":"2020-11-27T04:40:47","date_gmt":"2020-11-27T04:40:47","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/return-json-response-from-controller-in-magento-2\/"},"modified":"2025-05-22T11:30:29","modified_gmt":"2025-05-22T06:00:29","slug":"return-json-response-from-controller-in-magento-2","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/return-json-response-from-controller-in-magento-2\/","title":{"rendered":"How to Return a JSON Response from Controller in Magento 2"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/meetanshi.com\/magento-2-extensions.html\" target=\"_blank\" rel=\"noreferrer noopener\">Magento 2 extension<\/a>&nbsp;development requires customization that fulfills the business requirements.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">While developing an extension, the developers may need customization that returns the data from the controller in the JSON format.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When we make the AJAX request, the controller is called. In many cases, when we call a specific controller, we need to return data. For such cases, if we return data in JSON format, it would be a convenient option, especially when we need to return multiple values.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For instance, when a customer selects the country, all the states of the selected country are being displayed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This post gives the programmatic solution to<em><strong>&nbsp;<\/strong><\/em>return a JSON response from controller in Magento 2.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Solution to Return a JSON Response from Controller in Magento 2:<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">1. Create&nbsp;<strong>registration.php<\/strong>&nbsp;at&nbsp;<strong><em>app\/code\/Vendor\/Module<\/em><\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n\nuse Magento\\Framework\\Component\\ComponentRegistrar;\n\nComponentRegistrar::register(\n    ComponentRegistrar::MODULE,\n    'Vendor_Module',\n    __DIR__\n);<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">2. Create&nbsp;<strong>module.xml<\/strong>&nbsp;at<strong><strong><em>&nbsp;app\/code\/Vendor\/Module\/etc<\/em><\/strong><\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;? xml version = \"1.0\"?>\n&lt;config xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n        xsi:noNamespaceSchemaLocation=\"urn:magento:framework:Module\/etc\/module.xsd\">\n    &lt;module name=\"Vendor_Module\" setup_version=\"1.0.0\">\n    &lt;\/module>\n&lt;\/config><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">3. Create&nbsp;<strong><em>index.php<\/em><\/strong>&nbsp;at&nbsp;<strong><strong><em>app\/code\/Vendor\/Module\/Controller\/Index<\/em><\/strong><\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n\nnamespace Vendor\\Module\\Controller\\Index;\n\nuse Magento\\Framework\\App\\Action\\Context;\nuse Magento\\Framework\\View\\Result\\PageFactory;\nuse Magento\\Framework\\App\\Action\\Action;\n\nclass Index extends Action\n{\n    protected $resultPageFactory;\n\n    public function __construct(Context $context, PageFactory $resultPageFactory)\n    {\n        parent::__construct($context);\n        $this->resultPageFactory = $resultPageFactory;\n    }\n\n    public function execute()\n    {\n        return $resultPage = $this->resultPageFactory->create();\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">4. Create<strong>&nbsp;ReturnJson.php<\/strong>&nbsp;at&nbsp;<strong><strong><em>app\/code\/Vendor\/Module\/Controller\/Index<\/em><\/strong><\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n\nnamespace Vendor\\Module\\Controller\\Index;\n\nuse Magento\\Framework\\App\\Action\\Action;\nuse Magento\\Framework\\App\\Action\\Context;\nuse Magento\\Framework\\Controller\\Result\\JsonFactory;\n\nclass ReturnJson extends Action\n{\n\n    private $resultJsonFactory;\n\n    public function __construct(JsonFactory $resultJsonFactory, Context $context)\n    {\n        parent::__construct($context);\n        $this->resultJsonFactory = $resultJsonFactory;\n    }\n\n    public function execute()\n    {\n        $resultJson = $this->resultJsonFactory->create();\n        return $resultJson->setData(['json_data' => 'come from json']);\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">5. Then, create&nbsp;<strong>routes.xml<\/strong>&nbsp;at<strong><strong><em>&nbsp;app\/code\/Vendor\/Module\/etc\/frontend<\/em><\/strong><\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?xml version=\"1.0\"?>\n&lt;config xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n        xsi:noNamespaceSchemaLocation=\"urn:magento:framework:App\/etc\/routes.xsd\">\n    &lt;router id=\"standard\">\n        &lt;route id=\"module\" frontName=\"module\">\n            &lt;module name=\"Vendor_Module\"\/>\n        &lt;\/route>\n    &lt;\/router>\n&lt;\/config><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">6. Create&nbsp;<strong>module_index_index.xml&nbsp;<\/strong>at&nbsp;<strong><strong><em>app\/code\/Vendor\/Module\/view\/frontend\/layout<\/em><\/strong><\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?xml version=\"1.0\"?>\n&lt;page xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" layout=\"1column\"\n      xsi:noNamespaceSchemaLocation=\"urn:magento:framework:View\/Layout\/etc\/page_configuration.xsd\">\n    &lt;body>\n        &lt;referenceContainer name=\"content\">\n            &lt;block name=\"module_index_index\" template=\"Vendor_Module::template_file.phtml\" cacheable=\"false\"\/>\n        &lt;\/referenceContainer>\n    &lt;\/body>\n&lt;\/page><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">7. Create&nbsp;<strong>template_file.phtml&nbsp;<\/strong>at&nbsp;<strong><em>app\/code\/Vendor\/Module\/view\/frontend\/templates<\/em><\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;fieldset class=\"fieldset\">\n    &lt;div class=\"field required\">\n        &lt;label class=\"label\"\n               for=\"json_out\">&lt;span>&lt;?php echo $block->escapeHtml(__('Output')) ?>&lt;\/span>&lt;\/label>\n        &lt;div class=\"input-box control\">\n            &lt;input name=\"json_out\" id=\"json_out\" title=\"&lt;?php echo $block->escapeHtml(__('Output')) ?>\"\n                   value=\"\" class=\"input-text required-entry\" type=\"text\">\n        &lt;\/div>\n    &lt;\/div>\n    &lt;div class=\"field\">\n        &lt;div class=\"primary\">\n            &lt;button type=\"submit\" class=\"action submit primary btn_put_json\">&lt;span>Put Json Data&lt;\/span>&lt;\/button>\n        &lt;\/div>\n    &lt;\/div>\n&lt;\/fieldset>\n&lt;script>\n    require(\n        [\n            'jquery'\n        ],\n        function (\n            $\n        ) {\n            $('body').on('click', '.btn_put_json', function () {\n\n                var self = $(this);\n                var url = \"&lt;?php echo $block->getUrl() . 'module\/index\/ReturnJson' ?>\";\n                try {\n\n                    $.ajax({\n                        url: url,\n                        type: 'POST',\n                        dataType: 'json',\n                        showLoader: true,\n                        success: function (data) {\n                            $(\"#json_out\").val(data.json_data);\n                        }\n                    });\n                } catch (e) {\n                }\n\n            });\n        });\n\n&lt;\/script>\u0325<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Done!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Please do consider sharing this post with Magento Community via social media.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Thank you.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Magento 2 extension&nbsp;development requires customization that fulfills the business requirements. While developing an extension, the developers may need customization that returns the data from the&#8230;<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[34],"tags":[],"class_list":["post-1415","post","type-post","status-publish","format-standard","hentry","category-magento"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1415","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=1415"}],"version-history":[{"count":3,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1415\/revisions"}],"predecessor-version":[{"id":14606,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1415\/revisions\/14606"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=1415"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=1415"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=1415"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}