Create a JavaScript array containing all the elements from a MySQL table

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.

Answer №1

var questionBank = [];
ajaxRequest("GET","../controller.php?func=get_puzzle", (puzzle) => {
    var allPuzzles = JSON.parse(puzzle);
    for (var j=0; j < allPuzzles.length; j++){
        questionBank.push([allPuzzles[j]]);
    }
});

give this a shot

Answer №2

The data you are receiving is not structured correctly for your parsing needs. It would be beneficial to have a response that resembles something like this:

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

If possible, it is recommended to modify the format of the response from the ajax call. Alternatively, if you do not have control over the response structure, you may need to adjust your parsing logic to handle unnecessary tokens (such as indexes used as keys). This could be a result of stringifying raw data from a table.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying/Concealing specific choices using jQuery

Greetings! I am in need of some assistance with my coding query. I have been working on a piece of code where selecting 'x' should reveal another dropdown, which seems to be functioning correctly. However, if I navigate three dropdowns deep and t ...

Step-by-step guide: Adding a Google Maps API key to your WordPress theme

Having an issue with Google Maps on my WordPress website. The error message displayed is: Google Maps API error: MissingKeyMapError I have obtained a Google Maps API key, but I am unsure where to insert it. I am not using a Google Maps plugin; instead, my ...

Leveraging the combination of <Form>, jQuery, Sequelize, and SQL for authentication and navigation tasks

My objective is to extract the values from the IDs #username-l and #pwd-l in an HTML form upon the user clicking the submit button. I aim to compare these values with those stored in a SQL database, and if they match exactly, redirect the user to a specifi ...

Sending blank AJAX data to a PHP function

I am facing a challenge where I need to utilize AJAX to send the ID of an element and a specific value (1,2,3) to a PHP document for validation. Despite successfully logging both values in the console, the PHP file always returns that the data is empty. ...

What is the best way to display a jQuery UI dialog when the page is reloaded?

I am trying to display a jQuery UI dialog when the user tries to reload or close the browser. Here is my code snippet: $(window).bind('beforeunload', function () { $("#confirm").dialog({ width: 500, modal: true, buttons: { ...

Transferring an array to PHP using AJAX

In this coding scenario, I initialize my array: let myArray = []; Within a loop, elements are added to the array as follows: myArray.push($(this).data('id')); // Example: [1, 2, 3, 4] Subsequently, I transmit this data to PHP using AJAX throu ...

Utilizing Office.js: Incorporating Angular CLI to Call a Function in a Generated Function-File

After using angular-cli to create a new project, I integrated ng-office-ui-fabric and its dependencies. I included in index.html, added polyfills to angular.json, and everything seemed to be working smoothly. When testing the add-in in Word, the taskpane ...

The OutlinedInput component from Material-UI seems to be struggling to display the startAdornment

Below is the code snippet. The start adornment is not displaying in the textfield, and there is no text appearing on the label. <InputLabel>Mobile Number</InputLabel> <OutlinedInput variant="outlined" ...

Print custom jQuery attribute to console or log output

I need help retrieving and displaying a custom jQuery attribute in either an alert or console. Despite attempting to use console.log() to access my custom data attribute, I am unable to see its value appear. The specific value I am trying to display is d ...

What is the best way to send data from a React.js application to AWS Lambda?

I'm having trouble sending data from my React application to an AWS Lambda function through API Gateway. Here is the code snippet from my React app: const exampleObj = { firstName: 'Test', lastName: 'Person' }; fetch(process.env.R ...

Assigning a class to a header upon loading the page from various sections at random

After scrolling, I used JavaScript to add a class to <header>. Here is the code snippet: $(window).scroll(function(){ var top = $(window).scrollTop(); if(top>=1){ $("header").addClass('bg-header'); } else ...

Is there a way to prevent Express.js from triggering a file download in the browser?

I am attempting to preview a Word document file in the browser using an iframe: <iframe style="float:right;" src="/ViewerJS/#../demo/ohm2013.odp" width='400' height='300' allowfullscreen webkitallowfullscreen></iframe> (Fo ...

Modifying multiple heading tags simultaneously with jQuery

Currently utilizing jQuery to append a string to all heading tags (h1, h2,..., h6) and display it on the screen. Seeking guidance specifically for the replacing aspect, and open to solutions using plain javascript as well. The code I have so far, which I ...

The requested function is nowhere to be found within the confines of my Controller module

While working on a personal project, I encountered an issue where a function from another class in a separate Java file is not being found, even though it is defined in the respective class. EventView.js: displayEvent(event){ this.EventTitle = event. ...

How to easily retrieve additional data and update a document using Meteor

I'm feeling a bit lost on the best approach for obtaining additional data, particularly using an API, and adding it to the existing list. Imagine we're implementing either an infinite scroll or a 'load more' button, when that action oc ...

Exploring the Functionality of worker-loader Inline

It was my understanding that the Webpack worker-loader configuration below: ... module: { rules: [ { test: /worker\.js/, loader: "worker-loader", options: { inline: 'fallba ...

Struggling to send data to Wufoo API using PHP and AJAX

I'm still getting the hang of PHP and attempting to send data to a Wufoo Form that includes the fields shown below: https://i.sstatic.net/yoOgy.png However, when trying to POST information to it, I keep receiving a 500: Internal Server Error along w ...

Leveraging React's UseEffect() to retrieve information from GraphQL

I am currently attempting to retrieve data from graphQL. I understand that by placing a function inside the react UseEffect(), I can trigger the function once the data is updated and structured. However, while working on a chatroom feature, I am facing an ...

What could be causing the issue of HTML Button not functioning properly with jQuery Webpack?

I'm currently using webpack to build my HTML and javascript files. I have a function defined in index.js and I've attempted the solutions mentioned here, but none of them seem to work for calling the function onclick button. Here is the HTML cod ...

Encountering a Keycloak Sign In Issue with NextAuth in a Next.js Application [next-auth][error][SIGNIN_OAUTH_ERROR]

Hey there, I'm currently in the process of setting up authentication for my Next.js application using NextAuth and Keycloak. Even though I've followed the documentation closely, I've hit a roadblock when trying to sign in with Keycloak. Her ...