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