I am hosting my site using XAMPP and I have a database connection I can reference.
I have 3 drop down menus titled: Translations, books, chapters. The data for each is stored in my db.
I want to use Vanilla JS to query the dropdown menu content for books based on the users input for translations.
Example: If the user selects “English”, the books dropdown display all English books as soon as English has been selected.
I want these dropdowns to update in real time using fetch if possible. I plan on using this multiple times, I would like to have the Query on my main page and the server / database connection on another.
How would I create a JS function to run a query based on the value of one dropdown menu and pull data from a connection referenced on another file?
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');
});