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.
<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 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>
public function ajaxAction()
{
$location = $this->getDoctrine()->getRepository('SnowFrontBundle:Location')
->find(1);
$output = var_dump($location);
return $output;
}
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With