How to return the correct content-type for JSON in CakePHP? How to return the correct content-type for JSON in CakePHP? ajax ajax

How to return the correct content-type for JSON in CakePHP?


I make Ajax calls to retrieve JSON content in all of my projects and I've never done most of what you're doing here. The extent of my controller code looks something like this:

public function do_something_ajaxy() {  Configure::write ( 'debug', 0 );  $this->autoRender = false;  /** Business logic as required */  echo json_encode ( $whatever_should_be_encoded );}

I make my Ajax calls via jQuery so I suppose that could make a difference, but it would surprise me. In this case, you're problem appears to be in the handler, not with the caller. I'd recommend removing lines 17-23 and replacing them with a simple echo json_encode ( array('response' => $actions[0]) ) statement.

You're also testing for $this->RequestHandler->isGet(). Try testing $this->RequestHandler->isAjax() instead. I'm not sure whether Ajax calls are recognized as by both their type and their method.


After reading this and this, I got the following to return "Content-Type:application/json":

Configure::write('debug', 0);$this->RequestHandler->respondAs('json');$this->autoRender = false;            echo json_encode($data);

With JQuery's $.getJSON method, I'm still getting

Resource interpreted as image but transferred with MIME type text/html.

But at least my data is parsing.


I've also just had this problem, and solved it by using:

$this->RequestHandler->respondAs('text/x-json');

Also make sure that "debug" in your config file is set to less than 2 otherwise the header will not be set.