Looking for solutions using plain vanilla JavaScript only, as I do not utilize Json or jQuery currently (I have come across several solutions on SE, but they all involve jQuery or Json).
There are two functions within a window.onload=function(){...
event handler. The first function fillArray(from,to)
involves an Ajax call structured like this:
function fillArray(from,to){
request = createRequest();
if (request == null) {
return;
}
var url= "Ajax_retrieveNames.php?indexFrom=" + from + "&indexTo=" + to;
request.open("GET", url, true);
request.onreadystatechange = populateArray;
request.send(null);
}
function populateArray(){
var xmlFrag=null;
if (request.readyState == 4) {
if (request.status == 200) {
xmlFrag = request.responseXML;
for(var i=indexFrom; i<=indexTo; i++){
fcArray[i]=new Array();
var f=xmlFrag.getElementsByTagName("first")[i].childNodes[0].nodeValue;
var l=xmlFrag.getElementsByTagName("last")[i].childNodes[0].nodeValue;
fcArray[i][0]=f;
fcArray[i][1]=l;
}
}else{
return;
}
}else{
return;
}
}
The second function showNextName()
handles the formatting and display of elements from the next (in this case, first) sub-array. Currently, the var arrayIndex
is set to 0:
function showNextName(){
displayQuestion() // Handles page formatting
document.getElementById('firstName').innerHTML=fcArray[arrayIndex][0];
document.getElementById('lastName').innerHTML=fcArray[arrayIndex][1];
updateArrayIndex(); // Acts as a counter that increments the variable arrayIndex
}
The issue lies in the script jumping into the second function, showNextName()
, before completing the Ajax call and populating the array. I have temporarily resolved this by inserting a timer between the two functions, but this feels cumbersome. Is there a more elegant way to ensure we do not prematurely enter showNextName()
or exit window.onload
until the Ajax call is finished and the array is populated?