I am using SYMFONY 3 and i want to parse a received JSON from controller using Ajax , the issue there that the JSON can't be read properly and returns undefined this is my code below :
Controller :
$em = $this->getDoctrine()->getManager();
$RAW_QUERY = 'SELECT id,DO_Date,DL_Design,DL_Qte,DL_MontantHT,DL_MontantTTC FROM `facture_ligne` WHERE facture_id=:id';
$statement = $em->getConnection()->prepare($RAW_QUERY);
// Set parameters
$statement->bindValue('id', $id);
$statement->execute();
$facture = $statement->fetchAll();
$serializer = $this->container->get('jms_serializer');
$reports = $serializer->serialize($facture,'json');
return new Response($reports);
My script in a the twig file :
function detailfacture{{ fact.id }} (id) {
var z= new XMLHttpRequest();
z.open("get","{{ path('Ajaxonify',{'id':fact.id}) }})",true);
z.send()
z.onreadystatechange = function result () {
var json=z.responseText;
if(json!="")
{
alert(json);
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[1].DL_MontantHT + "</td>");
tr.append("<td>" + json[1].DO_Date + "</td>");
tr.append("<td>" + json[1].DL_Qte + "</td>");
$('#tb').append(tr);
}
}
else alert("helo");
}
}
And this some screen shots of the results :
I just tested with a static JSON and it works fine
This is what
console.log(data);
console.log(json);
returns
You need to parse the JSON into a JavaScript object before using it, like this:
Insert this line after
alert(json)
but before thefor
loop, so your script looks like this: