Receiving a json response in Symfony 2

ajax, jquery, json, symfony

Solution

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".

Problem

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 %} ```

Original source