Question: I am facing a dilemma on how to save form input data to a MySQL database while also using socket.io, as the preventDefault function seems to be causing issues. My current setup involves submitting form data via post requests and then storing it in the database through my express app.
Previously:
**index.ejs**
<form class='form' role='form' action='/users' method='POST'>
<input class='form-input' name='Client[FName]' type='text' />
<input class='form-input' name='Client[LName]' type='text' />
etc..
</form>
**server.js**
router.post('/users', (req, res) => {
const post = req.body.Client
pool.query('INSERT INTO Client SET ?', post, (err, result) => {
res.redirect(`users/${result.insertId}`);
})
})
The introduction of socket.io for real-time updates caused me to have to prevent default form submission:
**index.js**
let form = document.querySelector('.form');
let inputs = document.querySelectorAll('input');
form.addEventListener('submit', (e) => {
e.preventDefault();
socket.emit('message', {
FName: inputs[0].value,
LName: inputs[1].value,
etc,
etc
})
})
**server.js**
io.on('connection', function(socket) {
socket.on('message', (message) => {
socket.broadcast.emit('message', message)
*sql insert statement here??*
})
});
The functionality of socket.io is successful in updating the DOM in real time. However, I now need to find a way to resume saving the data to MySQL. Is there an alternative solution to inserting a query into the socket.io function or setting a timeout in the event listener?
I appreciate your assistance with this matter. Thank you.