Sunday, March 27, 2011

Setting the right JSON headers

Hi,

I am trying to return a JSON datastructure with the cakePHP framework.

But i am missing a part. The json encoded data which is returned has
the header: Content-Type : text/html and i would like it to be
application/json.

How to i can i manage this?

routes.php
Router::parseExtensions('json');

My app_controllers before filter:

function beforeFilter(){
//If the ext is the default(html) then we will set the
appropiate HTML layout
if(!isset($this->params['url']['ext']) || $this-
>params['url']['ext'] == 'html'){
($this->params['admin']) ? $this->layout = 'admin' :
$this->layout = 'guest';
}else{
if($this->params['url']['ext'] == 'json'){
$this->RequestHandler->setContent('json');
}else{
//Fallback to the defaul html
($this->params['admin']) ? $this->layout =
'admin' : $this->layout = 'guest';
}
}
}

views/layouts/json/default.ctp:
(If i uncomment what is commented out i get a file returned with the
json content inside it)
<?php
/*
header('Pragma: no-cache');
header('Cache-Control: no-store, no-cache, max-age=0, must-
revalidate');
header('Content-Type: text/x-json');
*/
echo $content_for_layout;
?>

views/controller/json/action
<?php
echo json_encode($values);
?>

What am i doing wrong?

Any help is greatly appricated.

--
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.


To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php

No comments: