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()
            $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:


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:


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


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.