HTTP Content-Type Header and JSON

Viewed 1004563

I have always been trying to avoid using most of the HTTP protocol's properties for the sake of fear of the unknown.

However, I said to myself that I'm going to face fear today and start using headers purposefully. I have been trying to send json data to the browser and use it right away. For example, if I have an Ajax handler function on ready state 4 which looks like so:

function ajaxHandler(response){
    alert(response.text);
}

And I have set the content-type header in my PHP code:

header('Content-Type: application/json');
echo json_encode(array('text' => 'omrele'));

Why can't I directly access the property from the handler function, when the browser is clearly told that the incoming data is application/json?

5 Answers

This is old but for me PHP8 it works if the charset is set example.

header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('text' => 'eggs'));

Recently ran into a problem with this and a Chrome extension that was corrupting a JSON stream when the response header labeled the content-type as 'text/html'.

Apparently extensions can and will use the response header to alter the content before the browser processes it.

Changing the content-type fixed the issue.

Related