title: How to store the output of an XMLHttpRequest in a global variable
body: <p>I have a webpage that will load a couple <code>JSON</code> files via <code>XMLHttpRequest</code>.<br>
  I want to load the file, parse the <code>JSON</code> and store the output in a globally accessible variable.<br>
  Once BOTH <code>foo</code> and <code>bar</code> are complete, only then do I want to call the <code>success()</code> function.  So far, my script has 2 problems that I need help with.  </p>
  
  <p>1: I'm having trouble setting the variable to the output of <code>loadJSON()</code>. My guess is that my return statements are a little funky?  I've tried everything... help?  </p>
  
  <p>2: How do I call <code>success()</code> only AFTER BOTH <code>foo</code> and <code>bar</code> are set?  </p>
  
  <pre><code>var foo;
  var bar;
  
  function initSession(){
  
      foo = loadJSON("foo.js");
      bar = loadJSON("bar.js");
  
  }
  </code></pre>
  
  <p>My guess is that the problem lies in how I'm using return in the <code>loadJSON()</code> function:  </p>
  
  <pre><code>function loadJSON(url){
  
      var xhr = new XMLHttpRequest();
  
      xhr.onreadystatechange = function(){
          if(xhr.readyState == 4 &amp;&amp; xhr.status == 200){  
              return JSON.parse(xhr.responseText);  // doesn't work?
          }
      }
  
      xhr.open("GET", url, true);
      xhr.send();
  
      return xhr.onreadystatechange;
  }
  
  
  
  $(document).ready(function(){
      initSession();
  });
  
  
  function success(){ 
      $("body").append(foo[0]);  
      $("body").append(bar[0]);  
  }
  </code></pre>
  
  <p>Thank you!  </p>