Technically, API stands for Application Programming Interface. At some point or another, large companies need to build APIs to serve easy access to their customers. To integrate third-party tool access, for such purpose JSON comes to the rescue. Basically, JSON means JavaScript Object Notation, which is a lightweight data-interchange format supported by Magento. Instead of using standard XML response, JSON helps to increase the productivity of the web applications by Minimizing the number of requests and amount of data transmitted between client and server.

Recently working on a custom extension development, we came across the requirement of using third-party API integration along with AJAX to save time and efforts of consumers. Keeping client’s requirement in mind and going through docs of API, we finally decided to use JSON response to reduce response time and data transmitted between extension and API server. To increase the efficiency of extension we have added a topping of AJAX to display data on the same page. Presenting guide to returning JSON data from controller While calling ajax in Magento 2.

By default, Magento has served a list of TYPE_JSON constant variables in ResultFactory. Magento\Framework\Controller\ResultFactory
Among which, here we have used json to fulfill the purpose but you can use any constant variable as per your requirement.
1. const TYPE_JSON = ‘json’
2. const TYPE_RAW = ‘raw’
3. const TYPE_REDIRECT = ‘redirect’
4. const TYPE_FORWARD = ‘forward’
5. const TYPE_LAYOUT = ‘layout’
6. const TYPE_PAGE = ‘page’

Firstly, create ‘Jsonrequest.php’ file in at below path using following code.
Because $this->resultFactory object is already defined in Magento\Framework\App\Action\Context we don’t need to create another.

Congratulations! You are done. You have successfully returned json data from controller. You can use or modify this code according to your convenience and requirement.

Lastly, comment down below if you are looking for any help regarding this code and tell us how you have used this code. Stay tuned for more.
Happy Coding!

Click to rate this post!
[Total: 12 Average: 4.2]