title: ajax request keeps returning last request
body: <p>I am trying to get ajax to return images for a internal gallery. I have it returning the images I want, the only problem is that the returned images is one request behind.</p>
  
  <p>E.g. If I called <code>return_img("test", 1, 5)</code> no images are returned but when I call <code>return_img("test", 6, 10)</code> images 1 to 5 form the test album are returned.</p>
  
  <p>My javascript code</p>
  
  <pre><code>function return_img(album, start, end) {
      vars = "album" + album + "&amp;start=" + start + "&amp;end=" + end;
      _("out").innerHTML = "";
  
      var request = new XMLHttpRequest();
      request.open("POST", "gallery_return_img.php", true);
      request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      request.onreadystatechange = function () {
          if (request.readyState === 4 &amp;&amp; request.status === 200) {
              var returned = request.responseText;
              returned = JSON.parse(returned);
              for (i = 0; i &lt; Object.keys(returned).length; i++) {
                  x = document.createElement("div");
                  y = document.createElement("img");
                  y.setAttribute("src", returned[i].url);
                  x.appendChild(y);
                  document.getElementById("out").appendChild(x);
              }
          }
      };
      request.send(vars);
  }
  </code></pre>
  
  <p>My PHP code</p>
  
  <pre><code>if (key_exists('album', $_POST) &amp;&amp; key_exists('start', $_POST) &amp;&amp; key_exists('end', $_POST)) {
      $album = $_POST['album'];
      $start = $_POST['start'];
      $end = $_POST['end'];
      $render = json_decode(file_get_contents("/gallery_images/$album/info.pics"));
      $total = count($render);
      if($end &gt; $total){
          $end = $total;
      }
      $pictures = [];
      for($start; $start &lt;= $end; $start++) {
          array_push($pictures, $render[$start]);
      }
  }
  </code></pre>
  
  <p>The info.pics file contains a JSON encoded list of the URLs and image names need to render the images in that album.</p>