How to return a JSON response with Symfony 1.4

JSON, the lightweight format that is used for data interchanging between applications, is widely used on every type of web application that has been written in any language e.g PHP, Ruby etc. To return a JSON response from an action in the legacy Symfony 1.4, you will need to change the content type of the response as first, otherwise you will end up returning a string without a specific header with the format that you're sending. The correct content type of JSON is application/json. Finally return the result of $this->renderText method of the symfony action that expects as first argument the JSON encoded string (use json_encode):


 * An actions.class.php file from any of the modules of your application.
class mymoduleActions extends sfActions 
     * Actualiza el estado de un módulo via AJAX.
     * @param sfWebRequest $request
     * @return type
    public function executeMyActionWithJsonResponse(sfWebRequest $request){
        // Your action logic

        // Set the response format to json
        // Use renderText to return a json encoded array !
        return $this->renderText(json_encode(array(
            "foo" => "bar"

The response of the MyActionWithJsonResponse action will be a JSON string namely:


Happy coding !

Become a more social person