Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

Plugin that returns JSON response?

Started by Muut Archive 10 years ago · 4 replies · 1995 views
10 years ago

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;
}

TXT


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

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

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

Not sure if related

10 years ago

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;
    }

    PHP
    /** @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));
    }
    }


10 years ago

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:

https://github.com/getgrav/grav-plugin-simplesearch/blob/develop/templates/simplesearch_results.json.twig

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1360 9 years ago
Archive · by Muut Archive, 9 years ago
2 938 9 years ago
Archive · by Muut Archive, 9 years ago
2 4068 9 years ago
Archive · by Muut Archive, 9 years ago
1 2958 9 years ago
Archive · by Muut Archive, 9 years ago
3 1122 9 years ago