Utilizing Vanilla JavaScript to retrieve information from a HTML table

I am currently running my website on XAMPP and I have a database connection set up that I can use.

In my database, I have three drop-down menus labeled Translations, Books, and Chapters where the data for each is stored.

My goal is to utilize Vanilla JS to dynamically query the content of the books dropdown based on the user's selection in the translations dropdown.

For instance, if a user chooses "English", the books dropdown should immediately display all English books available.

I am looking to implement real-time updates for these dropdowns using fetch, if feasible. As I plan to use this function multiple times, I would like to separate the query code on one page and keep the server/database connection logic on another.

How can I create a JavaScript function that will execute a query based on the selected value from one dropdown menu and fetch data from a connection specified on another file?

Here is an example:

book.html

async function fetchBooks() {
  const selectedTranslation = document.getElementById('translations').value;

  try {
    const response = await fetch(
      `/getBooks?translation=${selectedTranslation}`,
    );
    const books = await response.json();

    const booksDropdown = document.getElementById('books');
    booksDropdown.innerHTML = '';

    books.forEach((book) => {
      const option = document.createElement('option');
      option.value = book;
      option.textContent = book;
      booksDropdown.appendChild(option);
      console.log(option);
    });
  } catch (error) {
    console.error('Error fetching books:', error);
  }
}

database.js

// server.js

const express = require('express');
const mysql = require('mysql');

const app = express();

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'dataBase',
});

app.get('/getBooks', (req, res) => {
  const selectedTranslation = req.query.translation;
  const query = `SELECT DISTINCT book FROM english`;

  connection.query(query, [selectedTranslation], (err, results) => {
    if (err) {
      console.error('Error fetching books:', err);
      res.status(500).json({ error: 'Failed to fetch books' });
    } else {
      const books = results.map((result) => result.book);
      res.json(books);
    }
  });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Answer №1

If you are using XAMPP, the server side is based on PHP. In order to establish a database connection, you will need to use PHP (unless you opt for NodeJS as your server side).

Next, create a method that can query your database and return data in a user-friendly format like JSON.

This method should then be accessed through a new API, which can be called from the client side using JavaScript for asynchronous data retrieval.

Upon receiving the data, update the UI to display it to the user effectively.

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

Can you explain the concept of an "include template" in the Express/Jade framework?

This informative source mentions the existence of include templates. Despite several searches, I couldn't locate specific documentation on them. Can you explain what they are? ...

An error occured upon loading FullCalendar: Uncaught TypeError - Unable to read property 'push' as it is undefined

First of all, thank you for your assistance. I've been trying to load FullCalendar (https://fullcalendar.io/) on my development environments but it doesn't seem to be working. When I check the console in Chrome, it shows me the following error m ...

Leverage TypeScript with AngularJS to validate interpolation and binding within HTML documents

While TypeScript can detect compile errors for *.ts files, the question arises if these benefits can be extended to AngularJS views/templates. Consider a scenario where the code snippet below is present: <div ng-controller="HomeController as home"> ...

Different ways to access a model from a separate route

Hi there, I have a question regarding my implementation efforts with Node, express, mongoose, and ejs template. I've spent over four hours trying to make it work but so far no luck. My specific query is how to call a model in order to fetch all the d ...

The combination of Apache2 and mysqldump is resulting in a significant increase in the load

Currently dealing with a puzzling issue that is causing quite the headache and I'm in need of some innovative ideas to troubleshoot and resolve it. Situation: My setup includes a Rails app (Apache2 w/ Passenger) on server A (Rails.A) The master DB ...

Transferring JSON data through AJAX to a PHP backend

I have been working on a solution to convert a CSV file into JSON and then send it to BigCommerce using their REST API. Initially, I planned to use Javascript for the entire process, and everything was successful until I encountered issues with CORS when t ...

Separating vendor and application code in Webpack for optimized bundling

Recently, I created a React+Webpack project and noticed that it takes 60 seconds to build the initial bundle, and only 1 second to append incremental changes. Surprisingly, this is without even adding my application code yet! It seems that the node_modules ...

How do I access the variable value from inside a function in jQuery?

Is it possible to extract the value from 'a = entry.username' outside of the function? I need to retrieve a value that is already being looped inside the function. $('#btnlogin').click(function(){ var usernamelogin = $(&apos ...

Using the array.prototype.map method on props in React.js results in an array that is devoid

Recently, I've started exploring the world of React and encountered a problem while attempting to convert the value of props into a JSX element using array.prototype.map(). You can learn more about this method at this link. Here is a snippet of a Rea ...

Change the behavior of JavaScript so that it executes when clicked, not when the

This script is currently set to run when the page loads: <script language="JavaScript"> j=parseInt(Math.random()*ranobjList.length); j=(isNaN(j))?0:j; document.write(unescape(ranobjList[j])); </script> Is there a way I can mak ...

The error message "TypeError: Trying to access properties of an undefined object (reading '800')" is being displayed

Every time I launch my application, I encounter the error message: "TypeError: Cannot read properties of undefined (reading '800')". import React, { useState } from 'react'; import { Menu, MenuItem, Avatar, Box, ThemeProvider} ...

Guide for implementing smooth fade in and out effect for toggling text with button click

I have this code snippet that toggles text on button click: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> function toggleText(){ ...

I'm wondering how I can design a utility function within my Redux module that can extract a specific subset of read-only data from the current state

I am currently utilizing redux to create a "helper function" inside my redux module that is responsible for fetching filtered data from the state based on a specified index. This specific data will be used to generate a form consisting of inputs depending ...

Retrieving a channel using its unique ID and then sending a message directly into it

I am attempting to retrieve a channel by its ID and then send a message to it, but I keep encountering an error when running the code. ERROR: Error sending message to welcome channel.: TypeError: Cannot read properties of undefined (reading 'send&apos ...

How can I determine the package version that is being used when requiring it in Node.js?

I am currently working on resolving an issue with a node module that does not have a package.json. The module contains references to cheerio and superagent: var log = console.log.bind(console), superagent = require('superagent'), cheerio ...

PHP loops are nested to efficiently parse a CSV file and insert its data into a database. However, the SQL insert statement fails unexpectedly

Currently, I am facing an issue with a function that involves taking a large csv file and inputting it into a 2d array. The csv file is exported from a database table containing various records. Here are the steps involved in the function: //A. Retrieve ...

What is the best way to implement a loop using JQuery?

<script> $(function() { $('.slideshow').each(function(index, element) { $(element).crossSlide({ sleep: 2, fade: 1 }, [ { src: 'picture' + (index + 1) + '.jpg' } ]); }); ...

Guide to displaying all files from firebase storage on a screen

I'm struggling to display all the files from my firebase storage. I've tried pushing them into an array, but I can only get one file name. Any ideas on how to push all the files into the fileName array? function Home() { const [fileURL, setFile ...

I encountered a Node.js 203 error specifically on my computer - could this be linked to a specific environment and is there a way to resolve it

Let me explain what happened: I was working on a Nodejs-express-angular example by Brian Ford the other day, and everything was running smoothly. update:----------------this part of problem has been solved---------- However, after a few hours (during wh ...

Refusing to cease downloading music on the local server through the embedded audio element

I was trying to setup background music on my website, but when I test it localhost, the music download instead of playing. However, when I tested with the full path, it played as expected. How can I prevent the download from happening in localhost? Here i ...