I have a .ejs file that displays a form that sends data to a MySQL database when submitted. Then, that same page renders two tables with the data from database. The thing is I cannot get the tables to refresh after submitting the form and I have to restart the server to view the new data.
Here's the index.js file (express app):
const express = require('express');
const app = express();
const db = require('./database');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
// set and use express evironment
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use('/public', express.static(path.join(__dirname, 'public'))); // to serve static files
let bodyParser = require('body-parser');
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
// load DB tables
let arribos = [];
db.connect(function(err) {
if (err) throw err;
db.query('SELECT * FROM sv_hotel_in ORDER BY hora_creacion DESC', function(err, result, fields) {
if (err) throw err;
arribos = result;
});
});
let partidas = [];
db.connect(function(err) {
if (err) throw err;
db.query('SELECT * FROM sv_hotel_out ORDER BY hora_creacion DESC', function(err, result, fields) {
if (err) throw err;
partidas = result;
});
});
// render hotel form page
app.get('/hotels', (req, res) => {
res.render('hotel_index', { arribos, partidas });
});
I think I know what happens. When I run the server, the variables 'arribos' and 'partidas' load with the current data from the database. But after I submit the form from the page, the variables are still the same, they're not fetching the new data and that's why I need to restart the server so they load again and display all the data. How can I fix this?
You can place your code inside route path callback like this.
app.get('/table-data', (req, res) => {
db.connect(err => {
if (err) {
return res.send(err.message)
}
db.query('SELECT * FROM sv_hotel_in ORDER BY hora_creacion DESC', (err,
result, fields) => {
if (err) {
return res.send(err.message)
}
res.send(result);
})
})
})