Im trying to fetch categories list from my database and put it in my javascript code so i can use it later. But I've encountered problems with this task - after returning this list to javascript - they are empty.
Here is my symfony2 controller action code:
public function fetchCategoriesAction(){
$categories = $this->getDoctrine()->getRepository('MyDataBundle:Category')->findAll();
$return=array("responseCode"=>200, "categories"=>$categories);
$return=json_encode($return);//jscon encode the array
return new Response($return,200,array('Content-Type'=>'application/json'));
}
Here is my js code:
var categories;
function categoriesLoad(){
var url=$("#categories_fetch").val(); //link to my controller
$.post(url,function(data){
if(data.responseCode==200 ){
categories = data.categories;
console.log(categories);
}else{
console.log("An unexpeded error occured.");
}
});
}
I'm running
$(document).ready(function() {
categoriesLoad();
});
But then after using console.log(categories) I'm getting empty objects, although their number match the number of records in the database.
I'm just starting programming in symfony2 and I'd appreciate any help :)
EDIT:
SOLVED
I've just changed my controller action code. Here it is updated:
public function fetchCategoriesAction(){
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new GetSetMethodNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$em = $this->getDoctrine()->getManager();
$categories = $em->createQuery(
'SELECT u
FROM MyDataBundle:Category u'
)->getResult();
$categories = $serializer->serialize($categories, 'json');
$return=array("responseCode"=>200, "categories"=>$categories);
$return=json_encode($return);
return new Response($return,200,array('Content-Type'=>'application/json'));
}
Now it works fine. Thanks to @Pawel and @SAM