1

I want to create a Joomla json response for an Ajax request. So, I followed the instructions here: JSON Responses with JResponseJson

I implement the following code in my controller:

use \Joomla\CMS\Response\JsonResponse; class RamControllerAjax extends JControllerLegacy { public function capitals() { try { $country = JFactory::getApplication()->input->get('country'); if ($country == 'UK') $capital = 'London'; elseif ($country == 'Spain') $capital = 'Madrid'; else $capital = "I don't know"; $capital_json = json_encode($capital); echo new JsonResponse($capital_json); } catch(Exception $e) { echo new JsonResponse($e); } } } 

When I call it with the URL: http://joomla_clasificados/index.php?option=com_ram&task=ajax.capitals&country=UK

I receive the correct json response:

{"success":true,"message":null,"messages":null,"data":"\"London\""} 

But inserted in the middle of a normal Joomla page. Like this: enter image description here

What I want is the json response alone. I tried some changes in the URL, like:

http://joomla_clasificados/index.php?option=com_ram&task=ajax.capitals&country=UK&format=json

that gives me the error:

Invalid controller: name='ajax', format='json' 

Same thing with format=raw variant.

What I am doing wrong ? How could I get only the json response?

1 Answer 1

2

To use format=json query parameter, the controller filename needs to be suffixed with the format, e.g. ajax.json.php. This is mentioned in the linked documentation:

If you are developing an MVC component, save such a controller in a file called mycontroller.json.php and place it inside your controllers folder. That controller is automatically executed if your request URL contains format=json.

2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.