Plugin that returns JSON response?

I’m trying to write a plugin that when called on /something returns a JSON, something like {“payload”: {…}}.

At the moment I have create a plugin that calls onPageInitialized. The dump shows the correct payload but it loads the 404 template. If I call the route via AJAX I get a 404 response instead of 200.

— php
public function onPageInitialized()
{
$resp = array(“payload” => array(“test” => “yay”));
$resp = json_encode($resp);
dump($resp);
return $resp;
}


How can I make the plugin return a status of 200 and just the JSON, no template, nothing, just plain text?

PS: I keep seeing my Apache error log flooded with messages like this:

PHP Notice:  Undefined index: HTTP_ACCEPT in /var/www/gravtest/system/src/Grav/Common/Errors/Errors.php on line 17

Not sure if related

I managed to get the JSON to show up in the page. I was still getting a 404 HTTP status when I navigated to the plugin’s route but it was fixed by creating an empty page on the same route.

Here’s the plugin code.

— php

<?php namespace Grav\Plugin; use Grav\Common\Plugin; class ContactmePlugin extends Plugin { /** * Activate plugin if path matches to the configured one. */ public function onPluginsInitialized() { if ($this->isAdmin()) { $this->active = false; return; } /** @var Uri $uri */ $uri = $this->grav['uri']; $route = $this->config->get('plugins.contactme.route'); if ($route && $route == $uri->path()) { $this->grav['output'] = $this->doJsonMagic(); } } function doJsonMagic() { echo json_encode(array(1,2,3,4,5)); } } ---

Without reading all your code, it’s simple to return json in Grav. We do it all the time. Basically it just means you make a request of a regular page/route with .json appended to the URL. This in turn processes the page, just like a regular HTML page, but when it goes to render, Grav looks for a .json.twig file to render it.

A good example of this can be found in the SimpleSearch plugin. You can make a query with /search by default and the results are returned by simplesearch_results.html.twig, but if you request /search.json you get the results returned by simplesearch_results.json.twig, and that has a twig json_encode filter applied:

Thank you, I’ll look into that plugin.