I am attempting to store my mysql table data in a JavaScript array. My goal is to push each element of the table into the array so that it looks like this:
array[0] = [question: information01, answer: information02...]
array[1] = [question: information11, answer: information12...]
However, when I execute my code, all the elements of the table are stored in the first element of the array, resulting in the following structure:
array[0] = [[question: information01, answer: information02...], [question: information11, answer: information12...]]
As a result, the array has a size of 0 instead of reflecting the size of the mysql table (I hope this makes sense).
var availableQuestions = [];
ajaxRequest("GET","../controller.php?func=get_enigme", (enigme) => {
var enigmeAll = JSON.parse(enigme);
for (var i=0; i < enigmeAll.length; i++){
availableQuestions.push(enigmeAll[i]);
}
});
function ajaxRequest(type,url,callback,data=""){
let request = new XMLHttpRequest();
request.open(type, url);
request.onload = function () {
switch (request.status){
case 200:
case 201: //console.log(request.responseText);
callback(request.responseText);
break;
default: console.log(request.status);
}
};
request.send(data);
}
When I use
console.log(availableQuestions.length)
within my ajaxRequest function, it correctly displays 2. However, outside of the function, it shows length = 0
, which I find confusing.
Can anyone provide insight into this issue?
Thank you in advance for your assistance,
EDIT : I tried putting my parse into another array within my for loop, but it did not solve the problem.