Home > Net >  Put all the element of a mysql table into javascript array
Put all the element of a mysql table into javascript array

Time:06-03

I would like to store my mysql table into a javascript array. I wish to push into my array every element of the table so I would be left with an array like this :

array[0] = [question: information01, answer: information02...]
array[1] = [question: information11, answer: information12...]

With my following code, all the elements of my table are stocked into the first element of my array, which gives me this :

array[0] = [[question: information01, answer: information02...], [question: information11, answer: information12...]] 

and so the array has a size of 0 instead of size of the mysql table (I hope it 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 do a console.log(availableQuestions.length) in my ajaxRequest it is saying 2, but when I do it outside of my function it is saying length = 0. Which I don't understand

Does anyone have an answer to my problem ? Thank you very much in advance for your answers,

CodePudding user response:

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

try this

CodePudding user response:

The response you are getting is not in the right format for your parsing to work. You would probably want to end up with something like:

[
    {
        id: 1,
        question: "Question1"
        answer: "Answer1"
    },
    {
        id: 2,
        question: "Question2"
        answer: "Answer2"
    }
]

For that to happen, the response you get from the ajax call should look similar. If you have control over how the response is built, it would be better to go ahead and modify it. If not, you're gonna need to extend the logic of parsing that response a bit, since it contains a lot of tokens that aren't really necessary (I'm seeing a lot of indexes as keys, probably as a result of stringifying some raw data that comes from the table).

  • Related