I have a legacy application in CakePHP 2.x
It has a method in a Controller that outputs JSON in a structure like this:
{"id":59,"name":"Association of Southeast Asian Nations (ASEAN)","n_grouptags":1}
The controller method used $this->response->type('json');
to set the content-type
in the response to application/json; charset=UTF-8
. All good.
What I noticed is that if the returned data becomes over a certain length, the content-type
is set to text/html; charset=UTF-8
without any changes to the code.
I've included some screenshots below which show this, including the response type.
Small amount of data (content type = application/json
- expected):
More data (content type = text/html
- unexpected):
In both cases I have checked that the JSON is valid using https://jsonlint.com/
Why is this? Does it depend on the length of the response as to how the browser treats it, or is this a CakePHP problem?
The PHP that is responsible for the output is as follows - but no changes have been made to this between the 2 different outputs given above:
$this->autoRender = false; // No View (template) is associated with this
$out = []; // Reset
// $tags is some data from a model
foreach ($tags as $k => $v) {
$n_grouptags = 123; // Actual number comes from a Model
$out[] = ['id' => $k, 'name' => $v, 'n_grouptags' => $n_grouptags];
}
$this->response->type('json'); // We *want* a JSON response
echo json_encode($out, JSON_FORCE_OBJECT); // Encode $out (the output) as JSON
Caching within the application is disabled: Configure::write('Cache.disable', true);