I am trying to make a JSON request which returns data on the someone's age, gender and emotion. I have got this code, and the response works as console.log(response)
shows the response, but when I try and use the JSON keys in if statements, I get this error message in Chrome: Uncaught TypeError: Cannot read property 'emotion' of undefined
at XMLHttpRequest.processRequest (test.html:15)
.
Code below.
var xhr = new XMLHttpRequest();
var url = "http://cors-anywhere.herokuapp.com/http://86.15.11.51:8081/getPersons?format=json"
xhr.open('GET', url, true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
response = JSON.parse(xhr.responseText);
var response2 = JSON.stringify(response, null, 4);
document.write(response2);
for (var i = 0; i < 1; i++) {
{
var imgArray = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg'];
var emotion = response[i]['emotion']
var gender = response[i]['gender']
var age = response[i]['age']
var basePath = "http://advertdemo.ga/adverts/" + emotion + "/" + gender + "/" + age + "/";
document.getElementById("demo").innerHTML = basePath;
function imgRandom() {
for (var i = 0; i < 18; i++) {
var rand = imgArray[Math.floor(Math.random() * imgArray.length)];
var image = new Image();
image.src = basePath + rand;
document.body.appendChild(image);
break;
}
}
imgRandom();
console.log(basePath + rand);
break;
}
}
}
}
<html>
<body>
</body>
</html>