Return json from controller

I have a controller where I want to render the template if it is a get request and if it is a post request I want to return json.
On the page is a form that does a post via xhr.

When I test this on my local machine it returns json, but on production it returns the template.
Any ideas why?


return function($page, $pages, $site, $kirby) {
  if($kirby->request()->is('POST')) {
    // do stuff
    echo json_encode($response);

  } else {
    // prepare some output
    return $output;


The purpose of having a controller is that it returns a data array to your template. You should not echo something from your controller.

Well I want to return a data array (json) , but not render the template if it is a post request.

Does your POST request come from an AJAX request?

Yes, I am using ‘fetch’

Then it would make sense to use a json content representation template for the post request with its own controller if necessary.

In any case the template should echo the data, not the controller.

Thank you very much! The content representation template works perfect.

One question though:
is there a kirby way to get a link to the json version of a page?

$page->url() . '.json'

seem a little bit hacky.

No, there isn’t. If you need this more often, you could create a custom jsonurl() method.