Global Javascript variable from AJAX JSON request

Viewed 569

Hi i am using this code for my AJAX JSON request but for some if i try to make jsonObj a global variable and console.log() it always comes up as undefined in the debugger console

To clarify my question, how can I retrieve a global variable from an AJAX JSON request

function loadJSON() {
  var data_file = "https://www.tutorialspoint.com/json/data.json";
  var http_request = new XMLHttpRequest();
  try {
    // Opera 8.0+, Firefox, Chrome, Safari
    http_request = new XMLHttpRequest();
  } catch (e) {
    // Internet Explorer Browsers
    try {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");

    } catch (e) {

      try {
        http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        // Something went wrong
        alert("Your browser broke!");
        return false;
      }

    }
  }

  http_request.onreadystatechange = function() {

    if (http_request.readyState == 4) {
      // Javascript function JSON.parse to parse JSON data
      var jsonObj = JSON.parse(http_request.responseText);

      // jsonObj variable now contains the data structure and can
      // be accessed as jsonObj.name and jsonObj.country.
      document.getElementById("Name").innerHTML = jsonObj.name;
      document.getElementById("Country").innerHTML = jsonObj.country;
    }
  }

  http_request.open("GET", data_file, true);
  http_request.send();
}
<h1>Cricketer Details</h1>

<table class="src">
  <tr>
    <th>Name</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>
      <div id="Name">Sachin</div>
    </td>
    <td>
      <div id="Country">India</div>
    </td>
  </tr>
</table>

<div class="central">
  <button type="button" onclick="loadJSON()">Update Details </button>
</div>

3 Answers
Related