views:

1331

answers:

3

Hi, I'm trying to set the content-type header for a JSON response accessed with an AJAX GET request. I've followed tutorials on blogs and the bakery but I always receive 'text/html' back from CakePHP. How do I set the content-type header correctly?

Here's my code at the moment: http://bin.cakephp.org/view/668011600

Any help would be appreciated.

Thanks,

-- Isaac

A: 

I am not sure (and, to be honest, I've never used CakePHP), but you may want to try to specify a second argument in the setContent method..

replace this:

$this->RequestHandler->setContent('json')

with this:

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

see this file for an example..

And
I've just tried this (I've tried similar secondary arguments before, but I thought I'd give it another go) and it doesn't work. I still get 'text/html' returned.
+2  A: 

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.

Rob Wilkerson
I tried doing that before - I just had 'return json_encode' (and I tried 'echo json_encode' too). I was told in the IRC channel that that was a bad way of doing it and the 'right way' is to use a view. I disagreed, but I did it anyway to comply. I'll test isAjax, but given that my ajax call is a get request, isGet should work too. I also make my ajax calls with jQuery.
I've just tried your suggestion (I simplified everything to echo json_encode and used isAjax instead of isGet) and I still get 'text/html' returned.
Sorry, Isaac. I forgot to loop back on this. The content type shouldn't matter as long as the content itself is valid JSON. I avoid views for stuff like this because it's an extra file doing essentially nothing. I have issues with clutter. :-)
Rob Wilkerson
A: 

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.

Ajtacka