I want to loop through my JSON result and get each object's value to sum them. Here is my JSON result :
[{"Duree":"01:00:00"},{"Duree":"00:30:00"},{"Duree":"01:00:00"}]
Then i do this in my Ajax method :
var xhr1 = getXhr();
xhr1.onreadystatechange = function(){
if(xhr1.readyState == 4 && xhr1.status == 200){
Selection = xhr.responseText;
for(var i = 0; i < Selection.length; i++) {
if (i != 0) {
start = tot;
}
else if (i === 0){
start = Selection[0];
}
if ((i + 1) >= Selection.length) {
end = Selection[i + 1];
tot = addTimes(start, end);
}
}
alert(tot);
}
};
My php code which generate my json input :
foreach($rep as $Intervention) {
if ($Intervention['Vacation'] == $idVacation) {
$Query = 'SELECT Duree FROM fairegammeoperatoire WHERE IDIntervention=:id';
$rep = $bdd->prepare($Query);
$custom = $Intervention['IDIntervention'];
$rep->bindParam(':id',$custom);
$rep->execute();
$Duree = $rep->fetch(PDO::FETCH_ASSOC);
$tot = $Duree;
array_push($total, $tot);
}
}
echo json_encode($total);
EDIT : Problem was the name of variable xhr used in JSON.parse that wasn't the good one. Has to be xhr1 and not xhr. TY ALL =D
Have you tried to parse it as json object: It has to be parsed, since the response will be read as string.
var xhr1 = getXhr();
xhr1.onreadystatechange = function(){
if(xhr1.readyState == 4 && xhr1.status == 200){
Selection = JSON.parse(xhr1.responseText);
for(var i = 0; i < Selection.length; i++) {
if (i != 0) {
start = tot;
}
else if (i === 0){
start = Selection[0].Duree;
}
if ((i + 1) >= Selection.length) {
end = Selection[i + 1].Duree;
tot = addTimes(start, end);
}
}
alert(tot);
}
};
Your json must be something like
<?php
$dataArray = array(array("Duree"=>"01:00:00"),array("Duree"=>"02:00:00"),array("Duree"=>"03:00:00"),array("Duree"=>"04:00:00"));
echo json_encode($dataArray);
?>