Categories
Programming

Magento – Returning JSON (for AJAX and API Calls) Response From Controller Action

Within your Magento Controller > Action you can use the below code to send a JSON response.

[php]
$this->getResponse()->setHeader(‘Content-type’, ‘application/json’);
$this->getResponse()->setBody($jsonData);
[/php]

Read this post on how to use Magento’s core helper to encode and decode JSON.

By Kathir Vel

An agile ebusiness & marketing consultant based in Edinburgh, Scotland, UK. ICT specialist with a MBA in marketing and strategy. Seasoned project manager with strong roots in advertising campaigns and film making. Loves photography and travelling.

8 replies on “Magento – Returning JSON (for AJAX and API Calls) Response From Controller Action”

This is so much easier/faster than using `$resultJsonFactory`, which requires passing another param into `__construct()`, which requires a `magento setup:di:compile` step that takes forever to run and will likely end in an error that might take you several hours to a day to troubleshoot, if at all.

Leave a Reply

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