Want to call multiple XMLHttpRequest base don how much data we have

Viewed 40

So I have some Javascript that does an XMLHttpRequest (xhr), on receival of response it does a second response (xhr2) to get remaining data.

But I have now split this second call into batches so that it has to call multiple times depending on how much data there. After the first request I know how many calls I haven to make

var batches = Math.ceil((counter.innerText.substring(0,counter.innerText.indexOf(" ")) - 100) / 1000);

But then I am just making multiple calls to xdr2, but this doesn't work because it closes after first call. So I realize I probably need to initialize multiple XMLHttpRequest based on the value of batches, but how do I define the onreadystatechange function succinctly.

function get_tracklist_data(path, cid, title)
{
    var xhr = new XMLHttpRequest();
    var xhr2 = new XMLHttpRequest();
    xhr.onreadystatechange = function()
    {
        if (this.readyState == 4 && this.status == 200)
        {
            var counter = document.getElementById("counter");
            counter.innerHTML = xhr.responseText.substring(0, xhr.responseText.indexOf(":"));

            var data    = document.getElementById("data");
            data.innerHTML = xhr.responseText.substring(xhr.responseText.indexOf(":") + 1);
    
            //Work out how many calls we need to make
            var batches = Math.ceil((counter.innerText.substring(0,counter.innerText.indexOf(" ")) - 100) / 1000);
            for(i=1; i<batches;i++)
            {
                xhr2.open('GET',path + '?cid=' + cid + "&title=" + title+"&batch=" + i, true);
                xhr2.send();
            }
        }
    };

    xhr2.onreadystatechange = function()
        {
            if (this.readyState == 4 && this.status == 200)
            {
                var data    = document.getElementById("tbody");
                data.innerHTML+=xhr2.responseText;
            }
        };
    xhr.open('GET',path + '?cid=' + cid + "&title=" + title +"&batch=0", true);
    xhr.send();
};

Update to make xhr2 local variable in loop, but doesnt seem to work properly Im getting the same data back multiple times.

function get_tracklist_data(path, cid, title)
{
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function()
    {
        if (this.readyState == 4 && this.status == 200)
        {
            var counter = document.getElementById("counter");
            counter.innerHTML = xhr.responseText.substring(0, xhr.responseText.indexOf(":"));

            var data    = document.getElementById("data");
            data.innerHTML = xhr.responseText.substring(xhr.responseText.indexOf(":") + 1);

            //Work out how many calls we need to make
            var batches = Math.ceil((counter.innerText.substring(0,counter.innerText.indexOf(" ")) - 100) / 1000);
            for(i=1; i<batches;i++)
            {
                var xhr2 = new XMLHttpRequest();
                xhr2.onreadystatechange = function()
                    {
                        if (this.readyState == 4 && this.status == 200)
                        {
                            var data    = document.getElementById("tbody");
                            data.innerHTML+=xhr2.responseText;
                        }
                    };
                xhr2.open('GET',path + '?cid=' + cid + "&title=" + title+"&batch=" + i, true);
                xhr2.send();
            }
        }
    };


    xhr.open('GET',path + '?cid=' + cid + "&title=" + title +"&batch=0", true);
    xhr.send();
};
2 Answers

here example using await fetch() and fetch().then()

function listenForButtonCollapse(buttonId, collapseId, buttonText) {
  let button = document.getElementById(buttonId);
  let section = document.getElementById(collapseId);
  if (section != null) {
    section.addEventListener('show.bs.collapse', function() {
      button.innerText = 'Hide ' + buttonText;
    });
    section.addEventListener('hide.bs.collapse', function() {
      button.innerText = 'Show ' + buttonText;
    });
  }
}

async function get_tracklist_data(path, cid, title) {
  let xhr = await fetch(path + '?cid=' + cid + "&title=" + title + "&batch=0");
  let responseText = await xhr.text()
  let counter = document.getElementById("counter");
  counter.innerHTML = responseText.substring(0, responseText.indexOf(":"));
  let data = document.getElementById("data");
  data.innerHTML = responseText.substring(responseText.indexOf(":") + 1);
  listenForButtonCollapse('show_focus_button', 'focus_id', 'Spotlight');
  listenForButtonCollapse('show_albums_button', 'albums_id', 'Albums');
  listenForButtonCollapse('show_tracks_button', 'tracks_id', 'Tracks');
  listenForButtonCollapse('show_works_button', 'works_id', 'Works');

  //Work out how many calls we need to make
  let batches = Math.ceil((counter.innerText.substring(0, counter.innerText.indexOf(" ")) - 100) / 1000);
  data = document.getElementById("tbody");
  for (i = 1; i < batches; i++) {
    fetch(path + '?cid=' + cid + "&title=" + title + "&batch=" + i)
      .then(resp => resp.text())
      .then(responseText => {
        data.innerHTML += responseText;
      })
  }
}

Using XMLHttpRequest: save xhr object into array then add parameter to the callback listXHR[i].onreadystatechange = function(x) then call x.target for current xhr object

function get_tracklist_data(path, cid, title) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var counter = document.getElementById("counter");
      counter.innerHTML = xhr.responseText.substring(0, xhr.responseText.indexOf(":"));

      var data = document.getElementById("data");
      data.innerHTML = xhr.responseText.substring(xhr.responseText.indexOf(":") + 1);

      //Work out how many calls we need to make
      var batches = Math.ceil((counter.innerText.substring(0, counter.innerText.indexOf(" ")) - 100) / 1000);
      var listXHR = []
      for (i = 1; i < batches; i++) {
        listXHR[i] = new XMLHttpRequest();
        listXHR[i].onreadystatechange = function(x) {
          if (x.target.readyState == 4 && x.target.status == 200) {
            var data = document.getElementById("tbody");
            data.innerHTML += x.target.responseText;
          }
        };
        listXHR[i].open('GET', path + '?cid=' + cid + "&title=" + title + "&batch=" + i, true);
        listXHR[i].send();
      }
    }
  };


  xhr.open('GET', path + '?cid=' + cid + "&title=" + title + "&batch=0", true);
  xhr.send();
};
Related