XF 2.2 Returning a json response as view

Orit

Active member
Hi
Using XF2.2
I am displaying a snippet of a post, and have a button under it.
after clicking the button (to display the entire post, on the same page), I'd like to increment the views as if the post was viewed on its own page.
I have a public controller, but can't figure out what type of view to return.

Checking the route itself, when setting:
PHP:
$reply = $this->view('', '', [
    'post_id' => 'none' //this is for checking the controller page
]);
$reply->setViewOption('skipDefaultJsonParams', true);
$reply->setResponseType('json');

return $reply;

does return a json, but without my data (which could be manipulated in XF\Mvc\Renderer\Json::renderView)

but when the route is called via ajax, it tries returning a full html page, and not just the json.

I even tried creating a new reply type, but this was not successful...

Is there a way to return a json view, or are all the view types full html with added content (message, error, view...)
If I try using an api controller, I need to use an api key, which makes it complicated...
I can also increment the views by connecting to the db and calling the query directly, but then I can't mark the post as viewed by the user...

Any tips on this?
Or is it just not possible?

thanks!!!
 
I've not done this specifically myself, but you could try setting the response type to "raw" and then use a View class with the renderRaw() function to set the response type to json and output the json at that point?

I use this method to return zip files or xml files generated by my addon.

So your controller will be calling return $this->view('MyViewClass', '', $viewParams);

... and your view class will be something like:

PHP:
class MyViewClass extends \XF\Mvc\View
{
    public function renderRaw()
    {
        $this->response->contentType('application/json');

        // generate your json
        $json = '';
       
        return $this->response->body($json);
    }
}

I don't know if this works for json - when I'm initiating the download of binary files, there's a few more steps.
 
Back
Top Bottom