caplod
November 25, 2020, 9:18am
1
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?
site/controllers/game.php
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.
caplod
November 25, 2020, 2:18pm
3
Well I want to return a data array (json) , but not render the template if it is a post request.
texnixe
November 25, 2020, 6:21pm
4
Does your POST request come from an AJAX request?
texnixe
November 25, 2020, 9:51pm
6
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.
caplod
November 26, 2020, 7:54am
7
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.
texnixe
November 26, 2020, 8:01am
8
No, there isn’t. If you need this more often, you could create a custom jsonurl()
method.