As a beginner in JS, I am attempting to iterate through the given JSON data:
myLogger - myLogger - JSON ARRAY - {"dummmysetsJSONArr":[{"entryID":"1","distance":"100","calories":"50"},{"entryID":"2","distance":"200","calories":"100"},{"entryID":"3","distance":"300","calories":"150"},{"entryID":"4","distance":"400","calories":"200"},{"entryID":"5","distance":"500","calories":"250"},{"entryID":"6","distance":"600","calories":"300"}],"success":1}
However, the output on my console is not as expected and shows:
myLogger - undefined - undefined - undefined
I have tried various solutions found at this source but none of them seem to work for me.
This is how I have attempted using a for loop:
for (var key in jsonarry) {
if (jsonarry.hasOwnProperty(key)) {
myLogger(jsonarry[key].entryID + " - " + jsonarry[key].distance + " - " + jsonarry[key].calories);
}
}
/*
for (var key in jsonarry) {
if (jsonarry.hasOwnProperty(key)) {
myLogger(jsonarry[0].entryID + " - " + jsonarry[1].distance + " - " + jsonarry[2].calories);
}
}
*/
Below is my complete JavaScript code:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var req = false;
var jsonarry;
try {
// most browsers
req = new XMLHttpRequest();
myLogger("myLogger - XMLHttpRequest() created");
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
myLogger("myLogger - req = new ActiveXObject(Msxml2.XMLHTTP);");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
myLogger("myLogger - req = new ActiveXObject(Microsoft.XMLHTTP);");
} catch (e){
}
}
}
if (!req) {
myLogger("req === false");
} else {
myLogger("req === true");
}
// Use onreadystatechange property
req.onreadystatechange = function() {
//myLogger("myLogger - req.onreadystatechange = function(){");
if(req.readyState == 4) {
myLogger("myLogger - req.readyState == 4");
if(req.status === 200) {
myLogger("myLogger - req.status === 200");
jsonarry = req.responseText;
myLogger("myLogger - JSON ARRAY - " + jsonarry);
myLogger(" ------------- ");
var obj = JSON.parse(jsonarry);
myLogger("jsonarry.length == " + jsonarry.length);
for (var key in jsonarry) {
if (jsonarry.hasOwnProperty(key)) {
myLogger(jsonarry[key].entryID + " - " + jsonarry[key].distance + " - " + jsonarry[key].calories);
}
}
/*
for (var key in jsonarry) {
if (jsonarry.hasOwnProperty(key)) {
myLogger(jsonarry[0].entryID + " - " + jsonarry[1].distance + " - " + jsonarry[2].calories);
}
}
*/
} else {
myLogger("myLogger - req.status == " + req.status);
}
//return req.status === 200 ? success(req.responseText) : error(req.status)
} else {
myLogger("myLogger - req.readyState != 4 i.e. req.readyState === " + req.readyState);
}
}
req.open("GET", 'http://www.dummyurl/dbread.php', true);
req.send(null);
}
function myLogger(content) {
if (window.console && window.console.log) {
console.log("myLogger - " + content);
}
}