Magento – AJAX "Headers already sent" error solved

While working with AJAX in Magento many of you might have received the following error like I did:


2013-05-02T10:25:15+00:00 DEBUG (7): HEADERS ALREADY SENT:
[0] /var/www/html/ecomm/app/code/core/Mage/Core/Controller/Response/Http.php:44
[1] /var/www/html/ecomm/lib/Zend/Controller/Response/Abstract.php:727
[2] /var/www/html/ecomm/app/code/core/Mage/Core/Controller/Response/Http.php:75
[3] /var/www/html/ecomm/app/code/core/Mage/Core/Controller/Varien/Front.php:188
[4] /var/www/html/ecomm/app/code/core/Mage/Core/Model/App.php:304
[5] /var/www/html/ecomm/app/Mage.php:599
[6] /var/www/html/ecomm/index.php:104

Generally what we do is we create a controller action, inside it do the processing and then echo the output.


public function testAjaxAction() {

//Do something

.

.

echo $output;

}

Magento uses response object to send output to the browser. The reason of getting a “Headers already sent” error is that these is some code being executed by the Magento application after the controller dispatch which is trying to set headers.

The quick solution to this problem will be to use exit; after echoing the output as below


public function testAjaxAction() {

//Do something

.

.

echo $output;

exit;

}

If you intend following the best coding practices then you should use the “Response” object and pass the AJAX response to the objects “setBody”  method as below


public function testAjaxAction() {

//Do something

.

.

$this->getResponse()->setBody($output);

}

This allows you to bypass the layout system and send the output directly to the browser, keeping the responsibility of sending the output with the response object.

If  you need to set some header values say for sending the AJAX response as XML, code similar to the following may be used in AJAX header


$this->getResponse()
->clearHeaders()
->setHeader('Content-Type', 'text/xml')
->setBody('Some Response');

Comments

Leave a Comment

Back to top