Joomla - Controller task that returns JSON data
Quick method in existing controller
You need to use jexit()
to return json data without any Joomla output.
public function run ( ) {
$data = array(
'foo' => 'bar'
);
echo json_encode( $data );
jexit();
}
Joomla 3.x Method
The better alternative is to create JSON controller and use JResponseJson to output JSON. The file name should have JSON suffix. For example, if your controller is an item, then your file name can be item.json.php
and you can add controller code something like below.
public function run ( ) {
$data = array(
'foo' => 'bar'
);
echo new JResponseJson($data);
}
The output will be json like below.
{"success":true,"message":null,"messages":null,"data":["foo": "bar"]}
Your ajax URL should have json parameter to trigger this json controller.
index.php?option=com_mycomponent&task=item.run&format=json
Use JResponseJson to inform errors and messages as well. Read complete documentation at the below location.
https://docs.joomla.org/JSON_Responses_with_JResponseJson
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).