Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SilverStripe how to return JSON headers

My controller method Foo() (which is called through AJAX request) prints a JSON to the page using json_encode($data). I'm trying to accompany the correct http headers by using

header('Content-Type: application/json');

But from my browser development tools I read the AJAX response:

Content-Type:text/html; charset=utf-8

I'm assuming the JSON headers aren't sent correctly. Is this the right way to send JSON headers?

like image 336
Semicolon Avatar asked May 22 '26 01:05

Semicolon


1 Answers

From a Controller context, you would add this header like so:

$this->getResponse()->addHeader('Content-type', 'application/json');

If you are doing it from outside of a Controller then you need to create a new SS_HTTPResponse object and return it with the added header, as above. Here's an example of silverstripe/graphql doing this (in a SilverStripe 4 module).

like image 90
scrowler Avatar answered May 24 '26 18:05

scrowler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!