phpjsonjoomlajoomla2.5

Joomla - Controller task that returns JSON data


I have the task run in my controller. I want it to return JSON data. As it stands, I am getting my JSON data wrapped inside the template HTML. How do I tell Joomla to just return JSON data from the controller? This is the function I have:

public function run  ( ) {

    JFactory::getDocument()->setMimeEncoding( 'application/json' );

    JResponse::setHeader('Content-Disposition','attachment;filename="progress-report-results.json"');

    JRequest::setVar('tmpl','component');

    $data = array(
        'foo' => 'bar'
    );

    echo json_encode( $data );

}

And this returns:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" dir="ltr">
...
</head>
<body class="contentpane">

<div id="system-message-container">
</div>
    {"foo":"bar"}
</body>
</html>

I would like to get:

{"foo":"bar"}

Solution

  • You don't need to build a special JSON view (view.json.php; or controller progressreports.json.php) to achieve that. The only thing you have to do is to echo the JSON string and close the application.

    public function run( )
    {
        JFactory::getDocument()->setMimeEncoding( 'application/json' );
        JResponse::setHeader('Content-Disposition','attachment;filename="progress-report-results.json"');
    
        $data = array(
            'foo' => 'bar'
        );
        echo json_encode( $data );
        JFactory::getApplication()->close(); // or jexit();
    }
    

    You only need a separate view (or controller), if you want to provide the same function with both HTML and JSON output (chosen by the caller).