6

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!

4 Answers 4

5

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

json_encode() expects an associative array. you cant directly encode entities. you can use JMS Serializer Bundle if you want to encode entities. I would just create an array with the values you want to encode (since it might not be all the entity's properties)
2

This is happening because json_encode() does not know how to serialize an object (other than StdClass) to JSON. There are at least two ways to solve this:

  1. If you are on PHP 5.4 or above, you can have your object implement JsonSerializable, which PHP will use when you call json_encode() on the object.
  2. If you are on PHP 5.3 or earlier, you can use Symfony's Serializer component to convert the object to JSON using a number of different methods. I won't explain how exactly to do that, since the documentation is pretty clear.

Comments

-1

Code example:

$entity = // Get some entity
$result = array(
    'id' => $entity->getId(),
    'name' => $entity->getName()
);

return new Response(json_encode($result));

Comments

-1

If you want to get back data, you have to use a query repository (dsl) and on your $query variable use the getArrayResult() method. That allows you to get an array directly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.