Returning JSON response from Magento controller action
Here’s quick example of how to return JSON response from Magento controller action. Assuming you have already created appropriate XML configuration and controller class/file, just add the following code to your action:
<?php
class ArchApps_JsonResponse_IndexController
extends Mage_Core_Controller_Front_Action
{
/**
* Example of single controller action returning JSON response
*/
public function jsonAction()
{
// Data to be converted to JSON and returned as response
$config = array('data' => array(1, 2, 3, 4, 5));
// Make sure the content type for this response is JSON
$this->getResponse()->clearHeaders()->setHeader(
'Content-type',
'application/json'
);
// Set the response body / contents to be the JSON data
$this->getResponse()->setBody(
Mage::helper('core')->jsonEncode($config)
);
}
}
If you want all actions of particular controller to return JSON, you can avoid copying some code over and over by
setting the response type within the preDispatch
action:
<?php
class ArchApps_JsonResponse_IndexController
extends Mage_Core_Controller_Front_Action
{
/**
* Make sure all responses for controller are returned as JSON
*/
public function preDispatch()
{
parent::preDispatch();
// Make sure the content type for all responses is JSON
$this->getResponse()->clearHeaders()->setHeader(
'Content-type',
'application/json'
);
}
/**
* Example of multiple controller actions returning JSON response
*/
public function jsonAction()
{
// Data to be converted to JSON and returned as response
$config = array('data' => array(1, 2, 3, 4, 5));
// Set the response body / contents to be the JSON data
$this->getResponse()->setBody(
Mage::helper('core')->jsonEncode($config)
);
}
/**
* Example of multiple controller actions returning JSON response
*/
public function anotherJsonAction()
{
// Data to be converted to JSON and returned as response
$config = array('data' => array(1, 2, 3, 4, 5));
// Set the response body / contents to be the JSON data
$this->getResponse()->setBody(
Mage::helper('core')->jsonEncode($config)
);
}
}