T.i.
T.i.

Reputation: 21

Where do I put $this->request->headers('Content-Type', 'application/json');

I'm trying to change the content-type to application/json in Kohana. I put this in an action in my controller:

$this->request->headers('Content-Type', 'application/json');
$this->content = json_encode($json_data);

The request however, has still the text/html content-type.

Where should I put $this->request->headers('Content-Type', 'application/json'); ?

Upvotes: 2

Views: 6715

Answers (3)

phpguru
phpguru

Reputation: 2371

The OP asked where to put it. If you're using a controller that extends Controller_Template, like I am, I just added Andrew Schmid's code example to my base controller's after() method (before parent::after()) and it worked great.

So:

Controller_Your_Controller extends Controller_Template {

   // Your controller actions

   public function after()
   {
       // Set the response content-type here
       $this->response->headers('Content-Type','application/json');
       parent::after();
   }
}

Upvotes: 1

Andrew Schmid
Andrew Schmid

Reputation: 256

To elaborate on Claudio's answer, yes you need to set the response header, not the request, like so

$this->response->headers('Content-Type','application/json');

Also, I'm not sure how you've implemented your controller, but it looks like it may be a template controller based on

$this->content = json_encode($json_data);

If you are using a template controller, make sure you set auto_render to FALSE.

Finally, set the response body with your json data

$this->response->body(json_encode($json_data));

Upvotes: 10

Claudio
Claudio

Reputation: 5980

Well, you need to edit the response headers.

http://kohanaframework.org/3.1/guide/api/Response#headers

Upvotes: 1

Related Questions