How to Return a JSON Response from Controller in Magento 2
Magento 2 extension development requires customization that fulfills the business requirements.
While developing an extension, the developers may need customization that returns the data from the controller in the JSON format.
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.
For instance, when a customer selects the country, all the states of the selected country are being displayed.
This post gives the programmatic solution to return a JSON response from controller in Magento 2.
Solution to Return a JSON Response from Controller in Magento 2:
- Create registration.php at app/code/Vendor/Module
123456789<?phpuse Magento\Framework\Component\ComponentRegistrar;ComponentRegistrar::register(ComponentRegistrar::MODULE,'Vendor_Module',__DIR__); - Create module.xml at app/code/Vendor/Module/etc
123456<? xml version = "1.0"?><config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"><module name="Vendor_Module" setup_version="1.0.0"></module></config> - Create index.php at app/code/Vendor/Module/Controller/Index
1234567891011121314151617181920212223<?phpnamespace Vendor\Module\Controller\Index;use Magento\Framework\App\Action\Context;use Magento\Framework\View\Result\PageFactory;use Magento\Framework\App\Action\Action;class Index extends Action{protected $resultPageFactory;public function __construct(Context $context, PageFactory $resultPageFactory){parent::__construct($context);$this->resultPageFactory = $resultPageFactory;}public function execute(){return $resultPage = $this->resultPageFactory->create();}} - Create ReturnJson.php at app/code/Vendor/Module/Controller/Index
12345678910111213141516171819202122232425<?phpnamespace Vendor\Module\Controller\Index;use Magento\Framework\App\Action\Action;use Magento\Framework\App\Action\Context;use Magento\Framework\Controller\Result\JsonFactory;class ReturnJson extends Action{private $resultJsonFactory;public function __construct(JsonFactory $resultJsonFactory, Context $context){parent::__construct($context);$this->resultJsonFactory = $resultJsonFactory;}public function execute(){$resultJson = $this->resultJsonFactory->create();return $resultJson->setData(['json_data' => 'come from json']);}} - Then, create routes.xml at app/code/Vendor/Module/etc/frontend
123456789<?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="standard"><route id="module" frontName="module"><module name="Vendor_Module"/></route></router></config> - Create module_index_index.xml at app/code/Vendor/Module/view/frontend/layout
123456789<?xml version="1.0"?><page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column"xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"><body><referenceContainer name="content"><block name="module_index_index" template="Vendor_Module::template_file.phtml" cacheable="false"/></referenceContainer></body></page> - Create template_file.phtml at app/code/Vendor/Module/view/frontend/templates
123456789101112131415161718192021222324252627282930313233343536373839404142434445<fieldset class="fieldset"><div class="field required"><label class="label"for="json_out"><span><?php echo $block->escapeHtml(__('Output')) ?></span></label><div class="input-box control"><input name="json_out" id="json_out" title="<?php echo $block->escapeHtml(__('Output')) ?>"value="" class="input-text required-entry" type="text"></div></div><div class="field"><div class="primary"><button type="submit" class="action submit primary btn_put_json"><span>Put Json Data</span></button></div></div></fieldset><script>require(['jquery'],function ($) {$('body').on('click', '.btn_put_json', function () {var self = $(this);var url = "<?php echo $block->getUrl() . 'module/index/ReturnJson' ?>";try {$.ajax({url: url,type: 'POST',dataType: 'json',showLoader: true,success: function (data) {$("#json_out").val(data.json_data);}});} catch (e) {}});});</script>̥
Done!
If you have problems regarding this blog, feel free to ask in the Comments section below.
It’s always a pleasure to help readers with the Magento 2 queries.
Please do consider sharing this post with Magento Community via social media.
Thank you.
Still need help? Hire our Adobe-certified Magento experts.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
2 Comments
how to read table data using ajax in magento2
Hello Ashvin,
You can use the below blog:
https://meetanshi.com/blog/load-model-data-by-custom-field-magento-2/
Thank You