Receiving a json response in Symfony 2

I have a javascript event listener on the search.html.twig page that will trigger an ajax request. In the example below, my goal is for the ajax call to be successful so the alert() message is executed.

I am used to the flat PHP approach:

echo json_encode($myAry);

Symfony's routing system makes returning an json response to ajax confusing. I am currently getting an internal server error 500.

I appreciate any advice on how to troubeshoot this. Thank in advance!

DefaultController

     public function showCompanyAction($id)
    {
        $repository = $this->getDoctrine()->getRepository('TestBundle:Company');
        //get company based on id

        //prepare json object

        //return it to search.html.twig
        return new JsonResponse(array('name' => 'hello'));  
    }

JQuery (search.html.twig)

{% block jquery %} 
    <script>
        $(function(){


            $.ajax({
                type: "POST",
                url: "../company/booth/2",
                dataType: 'json',
                success: function(msg){
                    alert(msg);
                }
            })
        });
    </script>

{% endblock %} 

Answers


To return a json response in Symfony2, you have to return this from the controller called by the route defined for company/booth/2:

use Symfony\Component\HttpFoundation\Response;

class YourController
{
    public function YourAction()
    {
        $response = json_encode(array('message' => 'hello'));

        return new Response($response, 200, array(
            'Content-Type' => 'application/json'
        ));
    }
}

The 200 in the response is the Http Status Code. 200 means "the request was fulfilled".


Jivan's answer is good, here is a more maintainable alternative:

use Symfony\Component\HttpFoundation\JsonResponse;

class YourController
{
    public function yourAction()
    {
        $response = new JsonResponse();
        $response->setData(array('message' => 'hello'));

        return $response;
    }
}

With this solution, you don't need to encode the array and specify the response headers (Content-Type and all). If the specificity of JSON responses change then you won't have to worry about updating your code.


To process a JsonResponse with jQuery, you can do it with the "each" function:

public function showCompanyAction($id)
{
    return new JsonResponse(
        array(
            array('name' => 'hello'),
            array('name' => 'bye'),
        )
    );  
}

{% block jquery %} 
<script>
    $(function() {
        $.ajax({
            type: "POST",
            url: "../company/booth/2",
            dataType: 'json',
            success: function(data) {
                $.each(data, function (index, element) {
                    alert(element.name);
                });
            }
        })
    });
</script>
{% endblock %}

Need Your Help

Class Library Namespace Hierarchy Not Working

c# dll namespaces class-library

I am trying to achieve the namespace hierarchy used in C# in my class library. Here is what I am trying to do:

Matlab: trasform to cell of strings

string matlab cell

Problem: I have postfix (137x25) cell that contain cell of char (Ex postfix(6,8)=postfix{6,8}{1,1}&lt;1x3char>). I want to trasform it in (137x25) cell of char.