for(var y=0 ; y<=23 ; y++)
{
AjaxRequest99 = null;
AjaxRequest99 = getXmlHttpRequestObject(); // method to initiate the request
if(AjaxRequest99.readyState == 4 || AjaxRequest99.readyState == 0)
{
AjaxRequest99.open("GET", "ajax.php?id=99&AreaID=" +encodeURIComponent(AreaID)+ "&month="
+encodeURIComponent(document.getElementById("cboMonths").value)+ "&TimeSlot=" +encodeURIComponent(y), true);
AjaxRequest99.send(null);
AjaxRequest99.onreadystatechange = function()
{
if(AjaxRequest99.readyState == 4)
{
var innerHTMLdata = AjaxRequest99.responseText.toString();
/* Fetch data from server and display. */
document.getElementById("timeDiv"+y).innerHTML = innerHTMLdata;
}/* end if */
}/* end function */
}/* end if */
}/* end if */
I am attempting to use ajax multiple times to populate data in a series of divs: precisely 24, starting with timeDiv0, timeDiv1, timeDiv2, timeDiv3...... timeDiv23. Each call corresponds to the TimeSlot value and respective div e.g. TimeSlot=0 goes into timeDiv0.
I realize that the ajax calls here are overriding each other but I'm unsure how to fix this issue without duplicating code blocks 24 times. Note, it works when executed singularly outside the for loop, but only fills one of the 24 divs.
The following code successfully loaded images in 24 divs:
for(var y=0 ; y<=23 ; y++)
document.getElementById("img"+y).src="ajax.php?id=15&AreaID=" +encodeURIComponent(AreaID);
I aim to achieve a similar outcome without unnecessary repetition of code. Any suggestions?
Update: I have resolved the issue. See below for the solution
for(var y=0 ; y<=9 ; y++)
{
testFunc(y, AreaID); // invoking an external function within the loop
}
An external function:
function testFunc(y, AreaID)
{
var AjaxRequest99 = null;
AjaxRequest99 = getXmlHttpRequestObject();
if(AjaxRequest99.readyState == 4 || AjaxRequest99.readyState == 0)
{
AjaxRequest99.open("GET", "ajax.php?id=16&AreaID=" +encodeURIComponent(AreaID)+ "&month="
+encodeURIComponent(document.getElementById("cboMonths").value)+ "&TimeSlot=" +encodeURIComponent(y), true);
AjaxRequest99.send(null);
AjaxRequest99.onreadystatechange = function()
{
if(AjaxRequest99.readyState == 4)
{
var innerHTMLdata = AjaxRequest99.responseText.toString();
/* Retrieve data from the server and render. */
document.getElementById("timeDiv"+y).innerHTML = innerHTMLdata;
}
}
}
}