0

Im having trouble figuring why I'm not able to build a string by adding other in a loop. Heres the JavaScript function:

function displayCountries(){
    var body = "<option value='select'>...</option>";

    var xhr = new XMLHttpRequest();
    xhr.withCredentials = false;

    xhr.addEventListener("readystatechange", function () {
    if (this.readyState === this.DONE) {
        var data = JSON.parse(this.responseText);

        for (var i=0;i < data.length;i++) {
            body +="<option value='" + data[i].name + "'>" + data[i].name + "</option>";
            console.log("<option value='" + data[i].name + "'>" + data[i].name + "</option>");

        }
    }
    });

    xhr.open("GET", "https://restcountries.eu/rest/v2/all?fields=name;");
    xhr.setRequestHeader("Accept","application/json");
    xhr.send(null);
    console.log(body);
    document.getElementById("country-select").innerHTML=body;
}

The first console log works out fine printing the data as I expect and to see if I had no syntax errors passing to html, but the body variable doesent add the string in the loop so the second log only prints out the option "...".

Ive read through this a couple this but cant figure out why this isnt working. Help would be appreciated.

Phil
  • 175
  • 8

1 Answers1

1

You are setting the innerHTML property way before the response is available.

I will suggest you to create an option element and append that inside the for loop:

function displayCountries(){
  var select = document.getElementById("country-select");
  select.innerHTML = "<option value='select'>...</option>";

  var xhr = new XMLHttpRequest();
  xhr.withCredentials = false;

  xhr.addEventListener("readystatechange", function () {
    if (this.readyState === this.DONE) {
      var data = JSON.parse(this.responseText);
      for (var i = 0;i < data.length; i++) {
        var o = document.createElement('option');
        o.value = data[i].name;
        o.text = data[i].name;
        select.appendChild(o);
      }
    }
  });

  xhr.open("GET", "https://restcountries.eu/rest/v2/all?fields=name;");
  xhr.setRequestHeader("Accept","application/json");
  xhr.send(null);
}
displayCountries();
<select id="country-select"></select>
Mamun
  • 66,969
  • 9
  • 47
  • 59