Outputting JSON - Best Practice

Permalink
Dear Community,

i have looked in the past for a good way to output JSON with Concrete5. That's very useful for AJAX requests.

There was two ways i have found:
1) Outputting something with print/echo and breaking up the script with exit/die (not good)
2) Creating a custom theme for ajax outputs with no header and footer (also not the best solution)

After analyze the Core i found a hidden Symfony method to handle that. In my opinion this is the best solution to output JSON to the browser.

Past this code into your Page Controller:

Header:
use Symfony\Component\HttpFoundation\JsonResponse;


Class:
public function my_ajax_method() {
    return new JsonResponse(
        $some_data
    );
}


Best regards
Fabian

fabianbitter
 
JohntheFish replied on at Permalink Reply
JohntheFish
Have a look at the core ajax helper.

Or if you do it manually, simply.
echo $json_string;
exit;