Reputation: 5395
I want to produce a JSON response. I've tried the following in my Controller methods:
public function removeFilter($id = null)
{
$this->autoRender = false;
header('Content-Type: application/json');
echo json_encode(['result' => 'filter_removed']);
}
Then following instructions at CakePHP3.4: How to send a json object response? I also tried:
public function removeFilter($id = null)
{
$this->autoRender = false;
return $this->response
->withType('application/json')
->withStringBody(['result' => 'filter_removed']);
}
Both of these give a Response Headers of Content-Type: text/html; charset=UTF-8
. There is no template associated with this Controller method, which is why autoRender = false
.
What's going wrong here?
CakePHP 3.5.13
Upvotes: 0
Views: 2898
Reputation: 3658
Please try this. withStringBody
accepts a string only.
// If you want a json response
return $this->response->withType('application/json')
->withStringBody(json_encode(['result' => 'filter_removed']));
CakePHP More Info
Upvotes: 6