title: Ajax callback is only called once on final iteration of loop
body: <p>[EDIT] new question about the callback [edit]</p>
  
  <p>I am trying to load some local text files using Ajax and Javascript, but I cannot get the callback to work properly.
  I have an outline of my code: </p>
  
  <pre><code> var theFiles = {
    one: null,
    two: null,
    three: null,
    four: null,
    five: null,
    six: null,
    seven: null
  };
  function callback(pos,arrayofwords) {
  
      theFiles[pos]=arrayofwords;
  }
  
  xhr = new XMLHttpRequest();
  
  var getFiles = function(theFiles,callback) {
    for (var p in theFiles) {
      console.log("in getFile: " + p);
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 &amp;&amp; xhr.status == 200) {
  
          callback(p,xhr.responseText.split(/\r?\n/));
        }
       };
  
      xhr.open("GET", p + ".txt", true);
      xhr.send();
    }
  }
  </code></pre>
  
  <p>Stored locally are the files one.txt, two.txt, three.txt etc...
  The callback is only executed once even though the for loop calls an open() for each key in theFiles. Only the last item in theFiles (seven) is populated.
  I don't understand why.</p>
  
  <p>UPDATE
  After being provided the answer by @xianshenglu I have discovered that the callback is actually not needed. This works as well</p>
  
  <pre><code>    var theFiles = {
    one: null,
    two: null,
    three: null,
    four: null,
    five: null,
    six: null,
    seven: null
  };
  
  
  
  var getFiles = function(theFiles) {
    for (let p in theFiles) {   //var to let
      let xhr = new XMLHttpRequest();  //move inside the loop
      console.log("in getFile: " + p);
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 &amp;&amp; xhr.status == 200) {
  
          theFiles[p]=xhr.responseText.split(/\r?\n/)); //no callback needed
        }
       };
  
      xhr.open("GET", p + ".txt", true);
      xhr.send();
    }
  }
  </code></pre>