sameer manek sameer manek - 6 months ago 17
Javascript Question

Symfony: cannot fetch all the rows in a table via jsonresponse

I am trying to fetch all the records in my "products" table via jsonresponse into my ajax script that could be further loaded in my twig template, but as of now the value returned is null by json,

following is my controller:

public function showAction($slug){
$em = $this->getDoctrine()->getManager();
if($slug == 'prod'){
$repo = $em->getRepository('SystemBundle:Products');
$q = $repo->createQueryBuilder('u');
return new JsonResponse($q);
}

}


following is my ajax function:

<script>
function fetchprod() {
$.ajax({
url: "/show/prod",
dataType: "json"
}).success(function(data){
$('#contaiber').html(JSON.stringify(data.sum));
});
}
fetchprod()
setInterval(function () {fetchprod()}, 3000);
</script>


and this is my markup (just a container div to see what is returned):

<div id="container">

</div>


I am not getting anything inside the div, but when I enter the url I can see "{}" displayed on the page (basically a blank array).

how can I solve this?
Thank you

Answer

Try this

$em = $this->getDoctrine()->getManager();
if($slug == 'prod'){
    $repo = $em->getRepository('SystemBundle:Products');
    $q = $repo->createQueryBuilder('u')
    ->getQuery();
    $products = $q->getResult();
    return new JsonResponse($products);
}
Comments