Magento Controller Action Return Json (for AJAX, API etc)
Feb 15, 2012 · 1 minute readCategory: magento
If you have a controller action that is designed to be accessed by AJAX requests or perhaps as part of a custom API system then you might like this snippet.
If you are working with the above scenario you likely would like to return pure JSON without any HTML etc. Also serving up the correct content type headers is going to be helpful, its not HTML, its JSON.
public function searchAction(){
$query = $this->getRequest()->getParam('query');
$json = Mage::getModel('mymodule/mymodel')->getSearchJson($query);
$this->getResponse()->setHeader('Content-type', 'application/json');
$this->getResponse()->setBody($json);
}