I am new to node.js, i want to know how to populate a select menu on page load with mysql values. I am using nodejs, expressjs and jade/pug. I am unable to find any solution in google.
Jade file:-
block sale
form(action = "/get_sale", method = "GET")
select(id="cbosale", name="cbosale", class="custom-select custom-select-sm")
each sale in ["24", "34"]
option(value="#{sale}") #{sale}
App.js file:-
app.get('/get_sale', function(req, res){
db.connect(function(err){
db.query("SELECT DISTINCT(SaleNo), Season FROM tcatalogue",function(err, result, fields){
Object.keys(result).forEach(function(key){
var row = result[key];
console.log(row.SaleNo)
})
})
})
})
Instead of the static values in the jade file, values should be fetched from the app.js file.
When you try to get the route you need to fire a select query on your database and send the data to pug along with render as:
app.get('/output',function(req,res,next){
con.query("SELECT * FROM tableName", function (err, result, fields)
{
if (err)
throw err;
else
res.render('output',{page_title:"Output",data:result});
});
});
Now your output.pug
page will be produced with the data which you can populate them as options for your select menu.
html
head
title= 'Output'
body
select
each variable in data
option(value=variable.saleNo)
Indent the code properly in pug.