in my Node.js project I have a post function with which I write data into my MySQL database. I would like to have some values as a dropdown on my add page. At the moment I can only write all data with text fields to the MySQL database.
I have already created dropdowns, but with these I can only display the data from the corresponding tables, but the selected value in the post function will not be applied, no matter what I have tried.
GET and POST function:
app.get('/add', function(req, res, next) {
connection.query("SELECT DISTINCT platform_platform FROM platform; SELECT DISTINCT art_art FROM art;", [1, 2], function (error, result, fields) {
if(error) {
req.flash('error', error)
res.render('games/add', {
data: ''
})
} else {
res.render('games/g-add', {
data: result[0],
data1: result[1],
g_name: '',
g_status: ''
})
}
});
})
app.post('/add', function(req, res, next) {
req.assert('g_name').notEmpty()
req.assert('g_status').notEmpty()
var errors = req.validationErrors()
if( !errors ) {
var game = {
g_name: req.sanitize('g_name').escape().trim(),
g_status: req.sanitize('g_status').escape().trim()
}
connection.query('INSERT INTO games SET ?', game, function(err, result) {
console.log(err);
console.log(result.length);
if(err) {
req.flash('error', err)
res.render('games/g-add', {
g_name: game.g_name,
g_status: game.g_status
})
} else {
res.render('games/g-add', {
g_name: '',
g_status: ''
})
}
})
}
else {
var error_msg = ''
errors.forEach(function(error) {
error_msg += error_msg + '<br>'
})
req.flash('error', error_msg)
res.render('games/g-add', {
g_name: req.body.g_name,
g_status: req.body.g_status
})
}
})
EJS:
<form action="/games/add" method="post">
....
<div class="form-group">
<h4>Platform</h4>
<select class="custom-select">
<% for (var i = 0; i < data.length; i++) { %>
<option>
<%= data[i].platform_platform %>
</option>
<% } %>
</select>
</div>
....
<div class="form-group">
<label class="col-form-label" for="inputDefault">Name:</label>
<input type="text" class="form-control" id="inputDefault" value="<%= g_name %>">
</div>
....
<input type="submit" value="POST" class="btn btn-danger">
</form>
I just know the two dropdowns are not included in the POST function, but I have no idea how to get the selected data to the POST function.