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:

  1. Create registration.php at app/code/Vendor/Module

  2. Create module.xml at app/code/Vendor/Module/etc

  3. Create index.php at app/code/Vendor/Module/Controller/Index
  4. Create ReturnJson.php at app/code/Vendor/Module/Controller/Index
  5. Then, create routes.xml at app/code/Vendor/Module/etc/frontend
  6. Create module_index_index.xml at app/code/Vendor/Module/view/frontend/layout
  7. Create template_file.phtml at app/code/Vendor/Module/view/frontend/templates

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.

4.8
(based on 16 Reviews)
How to Return a JSON Response from Controller in Magento 2Author Magento Badge

Sanjay Jethva

Sanjay is a co-founder at Meetanshi. He is a Certified Magento Developer who loves creating Magento E-commerce solutions. Owing to his contributions in Magento Forums and posting solutions, he is among the top 50 contributors of the Magento community in 2019. When he is not engrossed with anything related to Magento, he loves to play cricket.

2 Comments

Leave a Reply

Your email address will not be published.