1. 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

Discussion in 'XenForo Development Discussions' started by Bogdan Tanase, Sep 27, 2014.

  1. Bogdan Tanase

    Bogdan Tanase Member

    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: Sep 27, 2014
  2. Mr. Goodie2Shoes

    Mr. Goodie2Shoes Well-Known Member

    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. Bogdan Tanase

    Bogdan Tanase Member

    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"}
    
     
  4. Mr. Goodie2Shoes

    Mr. Goodie2Shoes Well-Known Member

    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);
        }
    }
     
  5. Bogdan Tanase

    Bogdan Tanase Member

    Awesome. It works now. Thank you!
     

Share This Page