• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

What is the proper way to ouput JSON from a custom Controller action

#1
Hi everyone,

I want to expose an API from a custom module, so I've created a new controller with the actions I need but I'm a bit puzzled about the appropriate way to ouput the needed data in JSON format.

Do I need to create a separate view just for this or there's some nice helper in the Xenforo library?

PHP:
class MyModule_ControllerPublic_Chat extends XenForo_ControllerPublic_Abstract {
    public function actionIndex()
    {
        $data = array('example_key' => 'example_value');
        $json = json_encode($data);
     
        // something like this would be nice :)
        // return $this->responseJson($json);
    }
}
 
Last edited:

Mr. Goodie2Shoes

Well-known member
#2
Hello,
XenForo already has a view renderer for JSON... so what you have to do is:
PHP:
class MyModule_ControllerPublic_Chat extends XenForo_ControllerPublic_Abstract
{
     public function actionIndex()
     {
         $data = array('example_key' => 'example_value');
         $this->_routeMatch->setResponseType('json');
         return $this->responseView('', '', $data);
    }
}
And you will get the json output :)
 
#3
Hey, thanks for the quick response.

I've tried the example above but I get this output:
Code:
{"templateHtml":"","css":"","js":"","_visitor_conversationsUnread":"0","_visitor_alertsUnread":"0"}
 

Mr. Goodie2Shoes

Well-known member
#4
oops... forgot about that :p
change the action return code to:
PHP:
return $this->responseView('MyModule_ViewPublic_Chat_Index', '', $data);
create the file and add the following code:
PHP:
class MyModule_ViewPublic_Chat_Index extends XenForo_ViewPublic_Base
{
    public function renderJson()
    {
        return json_encode($this->_params);
    }
}