Learn how to return a JSON string as response from an action in 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):

<?php

/**
 * 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
        $this->getResponse()->setHttpHeader('Content-type','application/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:

{"foo":"bar"}

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors