Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom Header Data in Joomla

I m trying to make json response for android application.

Here is the code

$document =& JFactory::getDocument();
$document->setMimeEncoding('application/json');
$document->setCharset('utf-8');

The above code is working fine. but when I add the following code it does not generate any response.

$temp['TOKEN'] = "abc";
$document->setHeadData($temp);

I want to get the same result which can be achieved by followin code.

header('TOKEN:abc');

I cant use the header() method in my code.

like image 622
Umar Bukhari Avatar asked Jan 09 '14 10:01

Umar Bukhari


1 Answers

// For Joomla 2.5 - 4.0 (deprecated)
JResponse::setHeader('token', 'ABC');

// For Joomla 3.1+ (recommended)
$app = JFactory::getApplication();
$app->setHeader('token', 'ABC');

Just make sure you are not closing the application in the component, or it won't have a chance to send these.

If you do, you'll have to flush the headers manually:

// For Joomla 2.5 - 4.0 (deprecated)
JResponse::sendHeaders();
JFactory::getApplication()->close();

// For Joomla 3.1+ (recommended)
$app->sendHeaders();
$app->close();

Note:

If the page has been requested with the ?format=json, you don't have to set up the JDocument as application have used JDocumentJson with proper mime and charset.

Tip:

Check out com_ajax which assists in building JSON responses and handling exceptions.

like image 147
piotr_cz Avatar answered Sep 30 '22 08:09

piotr_cz