2

I have this function. With xhr.response I get my json values. Question: how do I attach these JSON values to my HTML labels? Thank you.

Unrelevant question: Does anyone know of a good website where beginning JSON concepts are compactly summarized?

For example country to the label country.

function initPage(){
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://ip-api.com/json", false);
    xhr.send();

    console.log(xhr.status);
    console.log(xhr.statusText);
    console.log(xhr);
    console.log(xhr.response);
}

JSON Output: Visit http://ip-api.com/json

Desired HTML:

<label id="landcode"></label>
<label id="country"></label>
<label id="regio"></label>
<label id="city"></label>
<label id="postcode"></label>
<label id="latitude"></label>
<label id="longitude"></label>
<label id="ip"></label>
Some Name
  • 561
  • 6
  • 18
  • 2
    What does the JSON look like and what did you want the HTML to end up looking like? You might also want to read and understand [this](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Matt Burland May 17 '17 at 15:30
  • Added JSON ouput and desired html. @MattBurland – Some Name May 17 '17 at 15:49

1 Answers1

4

You are doing XMLHttpRequest() call, you need to check if the status == 200 (2xx Success / 200 OK) and readyState = 4 (DONE):

enter image description here

<button type="button" onclick="initPage()">Change Content</button>
<br>
<label id="country">Before XMLHttpRequest CALL</label>

<script>
  function initPage() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("country").innerHTML =
          this.responseText;
      }
    };
    xhr.open("GET", "http://ip-api.com/json", false);
    xhr.send();

    console.log(xhr.status);
    console.log(xhr.statusText);
    console.log(xhr);
    console.log(xhr.response);
  }
</script>
Dalin Huang
  • 11,212
  • 5
  • 32
  • 49