title: Retrieving JSON data read with ajax and callback function
body: <p>Apologies for the very beginner question.</p>
  
  <p>I'm trying to use <a href="https://stackoverflow.com/a/14388512/1514952" title="this answer">this answer</a> to read in data in a JSON file into my javascript. I've pasted the code from the answer directly into the top of my javascript (changing <code>pathToFile.json</code> obviously). What I'm not sure about is what I'm supposed to do where the "do something with your data" comment is. I just want to have the parsed <code>data</code> object available to the rest of my code, but being extremely new to javascript I don't really understand how the callback function works. I can see the data from the JSON file logged in the console when I run it but every (no doubt dumb) thing I've tried to do to 'get it out' of the function hasn't worked -- I get a <code>ReferenceError: data is not defined</code> message when I try to refer to it later.</p>
  
  <p>Here's the code from the other answer:</p>
  
  <pre><code>function fetchJSONFile(path, callback) {
      var httpRequest = new XMLHttpRequest();
      httpRequest.onreadystatechange = function() {
          if (httpRequest.readyState === 4) {
              if (httpRequest.status === 200) {
                  var data = JSON.parse(httpRequest.responseText);
                  if (callback) callback(data);
              }
          }
      };
      httpRequest.open('GET', path);
      httpRequest.send(); 
  }
  
  // this requests the file and executes a callback with the parsed result once
  //   it is available
  fetchJSONFile('pathToFile.json', function(data){
      // do something with your data
      console.log(data);
  });
  </code></pre>