0

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>
Barmar
  • 741,623
  • 53
  • 500
  • 612
Jonny Drift
  • 53
  • 1
  • 12
  • 1
    how `response` look like? – brk May 05 '18 at 14:26
  • { "persons": [ { "age": "adult", "attentive": true, "duration": 2914, "emotion": "neutral", "face": { "absolute": { "size": 216, "x": 346, "y": 312 }, "relative": { "size": 0.452083, "x": 0.54182, "y": 0.651205 } }, "gender": "male", "id": 332 } ] } – Jonny Drift May 05 '18 at 14:27

2 Answers2

1

Your response is not array (!) - so why U use for and index it like array

you should do it in this way:

response['persons'][0].emotion

and DONT't hardcode upper index in for loop: for (var i = 0; i < 1; i++).

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
1

Try by accessing the persons and then the emotion.The value of persons key is an array. Assuming the response have only one key persons, use 0 to get the element from the 0 index

response.persons[0].emotion

brk
  • 48,835
  • 10
  • 56
  • 78