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!
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.
If you want to get back data, you have to use a query repository (dsl) and on your
$query
variable use thegetArrayResult()
method. That allows you to get an array directly.Code example:
This is happening because
json_encode()
does not know how to serialize an object (other thanStdClass
) to JSON. There are at least two ways to solve this:JsonSerializable
, which PHP will use when you calljson_encode()
on the object.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.