Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 %} 
like image 366
AnchovyLegend Avatar asked Mar 21 '23 17:03

AnchovyLegend


2 Answers

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.

like image 122
Thomas Potaire Avatar answered Mar 23 '23 20:03

Thomas Potaire


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

like image 32
Jivan Avatar answered Mar 23 '23 19:03

Jivan