Creating LIs on the fly doesn't work as I want
I have a Symfony 2 function called via AJAX from the template. This is the
function:
/**
* Get subcategories based on $parent_id parameter
*
* @Route("/category/subcategories/{parent_id}",
name="category_subcategories", options={"expose"=true})
* @Method("GET")
*/
public function getCategories($parent_id = null) {
$em = $this->getDoctrine()->getManager();
$entities =
$em->getRepository('CategoryBundle:Category')->findBy(array("parent"
=> $parent_id));
$subcategories = array();
foreach ($entities as $entity) {
$subcategories[] = array($entity->getId() => $entity->getName());
}
$response = new JsonResponse();
$response->setData($subcategories);
return $response;
}
That functions returns a JSON like this:
[{"27":"Test10"},{"28":"Test11"},{"29":"Test12"}]
So I wrote this jQuery function to parse and display elements:
$(function() {
$("a.step").click(function() {
var id = $(this).attr('data-id');
$.ajax({
type: 'GET',
url: Routing.generate('category_subcategories', {parent_id: id}),
dataType: "json",
success: function(data) {
if (data.length != 0) {
var LIs = "";
$.each(data[0], function(i, v) {
LIs += '<li><a class="step" data-id="' + i + '"
href="#">' + v + '</a></li>';
});
$('#categories').html(LIs);
}
}
});
});
});
But it's not working because only the first element of the JSON array is
showed, what is wrong in my code? Any advice?
No comments:
Post a Comment