0

This code is meant to send a JSON request and store it under the variable json. It is then meant to display a picture depending on the value of a key (specifically if the key gender = male). No picture is displaying and I can't find a solution anywhere so is anyone able to help?

var i=20
while (i<10)
{var json = new XMLHttpRequest();
json.open('GET', "http://localhost:8081/getPersons?format=json", true);
json.send();
 
json.onreadystatechange = processRequest;
function processRequest(e) {
    if (json.readyState == 4 && json.status == 200) {
        var response = JSON.parse(json.responseText);
        alert(response.ip);
    }
}
var wantedKey = 'gender'; // your key here
var wantedVal = 'male'; // your value here

for(var i = 0; i < json.length; i++){

   if(json[i].hasOwnProperty(gender) && json[i][gender] === male) {
    document.createElement("img");
    img.src = "http://advertdemo.ga/adverts/emotion_neutral/male/young/iphone.jpg";
    img.width = "300px";
    img.height = "300px";

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
    break;
   }

}}
Jonny Drift
  • 53
  • 1
  • 12
  • You have multiple problems, first you declare an variable `i` at the top and an `i` variable for your loop, they are going to interfere with each other. Next you set `i` to `20` and your while loop's condition is to run while `i` is less than 10 but it isn't so your while loop will never run. – Patrick Evans May 03 '18 at 19:36
  • you forgot to assign it document.createElement("img"); to img variable. – BugHunter May 03 '18 at 19:37
  • @PatrickEvans, just noticed that myself. Thank you – Jonny Drift May 03 '18 at 19:39
  • @BugHunter I've just done that `img = document.createElement("img");` but same problem still applies. – Jonny Drift May 03 '18 at 19:41
  • @PaulAdams, male is not variable, json[i][gender] === "male" – BugHunter May 03 '18 at 19:45
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Sebastian Simon May 03 '18 at 20:20

2 Answers2

0

There are a multitude of problems with your code, most importantly that you seem to misunderstand how AJAX works. Here's my fix with comments on what was wrong and where.

var json = new XMLHttpRequest();
json.open('GET', "http://localhost:8081/getPersons?format=json", true);
json.send();

// It's better to declare event handlers this way,
// your version relied on variable hoisting (look it up),
// which is not usually recommended.
json.onreadystatechange = function(e) {
    if (json.readyState == 4 && json.status == 200) {
        var response = JSON.parse(json.responseText);

        // This was the main problem:
        // Processing the result of the XHR should be *inside* the
        // readystate (or load) event handler
        for (var i = 0; i < response.length; i++) {
            // You forgot to put the property name "gender" in quotes
            // as well as the value "male"
            // Also, the double check was unnecessary. This is perfectly safe.
            if(response[i]['gender'] === 'male') {
                var img = document.createElement("img");
                img.src = "http://advertdemo.ga/adverts/emotion_neutral/male/young/iphone.jpg";
                // You should set dimensions on the style property,
                // not img directly
                img.style.width = "300px";
                img.style.height = "300px";

               document.body.appendChild(img);
               break;
            }
        }
    }
}
Máté Safranka
  • 4,081
  • 1
  • 10
  • 22
  • Thank you so much for correcting this - I haven't used AJAX before. It still doesn't work, do you know why? – Jonny Drift May 03 '18 at 20:00
  • There could be any number of reasons -- this is where you start debugging. Open up the browser's developer tools, and check the Console tab for error messages, and the Network tab to make sure your AJAX request is sent to the server and a response is received. You can also use `console.log()` in your code to write data and messages to the console from your own code, to make sure your code is executing and variables contain the data they should. – Máté Safranka May 03 '18 at 20:14
  • Thanks for the advice. I did that but I don't think the if statement (response of gender = male) is being met, because putting `console.log()` outside of it worked, but not inside. I am sure that there is a key in the JSON called "gender" and the value "male" however. The JSON HTTP address is correct too. – Jonny Drift May 04 '18 at 07:14
  • Try `console.log(response)` after parsing the AJAX result to see what your code sees. – Máté Safranka May 04 '18 at 07:17
  • I have done a bit of testing and discovered the source of my problem. For some reason, the code doesn't work with localhost addresses. I know, because I tested it with ipinfo.io/json instead and it worked. I am running code with the Chrome with the `--disable-web-security` flag, but it still doesn't work. Do you have any advice? – Jonny Drift May 04 '18 at 19:46
-1

try this:

var i=20
while (i<10)
{var json = new XMLHttpRequest();
json.open('GET', "http://localhost:8081/getPersons?format=json", true);
json.send();
 
json.onreadystatechange = processRequest;
function processRequest(e) {
    if (json.readyState == 4 && json.status == 200) {
        var response = JSON.parse(json.responseText);
        alert(response.ip);
    }
}
var wantedKey = 'gender'; // your key here
var wantedVal = 'male'; // your value here

for(var j = 0; j < json.length; j++){

   if(json[i].hasOwnProperty(gender) && json[i][gender] === male) {
    img= document.createElement("img");
    img.setAttribute("src", "http://advertdemo.ga/adverts/emotion_neutral/male/young/iphone.jpg");
    img.setAttribute("width", "300");
    img.setAttribute("height", "300");

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
    break;
   }

}}
majidse
  • 19
  • 4