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();
};