How to add custom Header Data in Joomla
Asked Answered
B

1

7

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.

Betsey answered 9/1, 2014 at 10:10 Comment(0)
N
11
// 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.

Navar answered 9/1, 2014 at 10:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.