Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 returns empty JSON on AJAX call while variable isn't empty

Problem

I'm trying to get an AJAX response so I can fiddle around with it to make my forms easier to use. When I make the controller (code below) return a normal response with var_dump(), I get the object's output so I know the query isn't wrong (I'm using ID 1 to query to debug). However, when I return the output with json_encode(), I just get an empty JSON file.

HTML form in the view

<div id="content">
    <form id="myForm" action="{{path('snow_ajax')}}" method="POST" >
        Write your name here:
        <input type="text" name="name" id="name_id" value="" /><br />
        <input type="submit" value="Send" />
    </form>
</div>

Script in the same view

<script type="text/javascript">
    $(document).ready(function() {

        $("#myForm").submit(function(){
            var url=$("#myForm").attr("action");

            $.post(url,{
                formName:"ajaxtest",
                other:"attributes"
            },function(data){

                if(data.responseCode==200 ){
                    alert("Got your json!");
                }
                else{
                    alert("something went wrong :(");
                }
            });
            return false;
        });
    });
</script>

Controller with normal response (works)

public function ajaxAction()
{

    $location = $this->getDoctrine()->getRepository('SnowFrontBundle:Location')
        ->find(1);

    $output = var_dump($location);

    return $output;
}

Controller with AJAX response (doesn't work, returns empty JSON)

public function ajaxAction()
{

    $location = $this->getDoctrine()->getRepository('SnowFrontBundle:Location')
        ->find(1);

    return new Response(json_encode($location), 200);
}

Could anyone help me out here, please? This is driving me nuts!

like image 935
thomastuts Avatar asked Jan 19 '13 11:01

thomastuts


1 Answers

I managed to fix it by using Doctrine2's entity manager to get the result in an array, after which I proceeded to encode it into JSON. I'm not sure if this is the cleanest way to do it (getEntityManager() seems to be deprecated according to my IDE) but it works fine for now.

public function ajaxAction()
{
    $em = $this->getDoctrine()->getEntityManager();
    $query = $em->createQuery('SELECT l FROM Snow\FrontBundle\Entity\Location l WHERE l.id=:id');
    $query->setParameter('id', 1);
    $result = $query->getArrayResult();

    return new Response(json_encode($result), 200);
}
like image 123
thomastuts Avatar answered Sep 28 '22 01:09

thomastuts