PHP Joomla! 6 Joomla! 5 Joomla! 3 (Legacy) Component Intermediate

Return Standardized JSON Responses in AJAX Endpoints with JsonResponse

Outputs structured {success, message, data} JSON payloads with proper Content-Type headers and clean $app->close() termination.

Updated on 24 November 2026 56 copies 192 views
components/com_example/src/Controller/AjaxController.php
<?php

declare(strict_types=1);

use Joomla\CMS\Factory;
use Joomla\CMS\Response\JsonResponse;

$app = Factory::getApplication();
$app->mimeType = 'application/json';
$app->setHeader('Content-Type', 'application/json; charset=utf-8', true);

try {
    $payload = ['status' => 'ok', 'total' => 100];
    echo new JsonResponse($payload, 'Consulta concluída');
} catch (\Throwable $e) {
    $app->setHeader('status', '400', true);
    echo new JsonResponse(null, $e->getMessage(), true);
}

$app->close();
Always pair with Session::checkToken() on state-changing AJAX actions.
components/com_example/src/Controller/AjaxController.php
<?php
$app = JFactory::getApplication();
echo new JResponseJson(array('status' => 'ok'), 'Consulta concluída');
$app->close();
Legacy Joomla 3 version using JResponseJson.

Technical explanation and best practices

Joomla\CMS\Response\JsonResponse automatically formats payloads, errors and queued application messages in the exact envelope expected by Joomla frontend scripts.

Direct Engineering

Have a Joomla project or technical challenge in mind?

From architectural diagnosis to production deployment, directly with the engineer.