0

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

Andy
  • 5,142
  • 11
  • 58
  • 131
  • 1
    The easiest and cleanest way is to use .json extension in your URL. See code behind [this sandbox example](https://sandbox.dereuromark.de/sandbox/ajax-examples/simple). – mark Jul 04 '18 at 12:09
  • 2022, CakePHP 3 and 4: [Try the built-in `RequestHandler`](https://stackoverflow.com/a/51859677/) – ᴍᴇʜᴏᴠ Jul 26 '22 at 10:23

1 Answers1

6

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

Rakesh Sojitra
  • 3,538
  • 2
  • 17
  • 34