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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With