I fill html table with data from database (user's emails and their roles in my system (admins and users)).
router.get('/adminOffice', function(req, res){
database.connection.query("select email, role from users", function(err, rows, fields){
if(err) console.log(err);
res.render('adminOffice', {rows: rows});
});
});
With the help of ejs it looks next (adminOffice.ejs):
<form method="post" action="saveRoles">
<table name="table" id="table"><tr>
<th>Email</th><th>Role</th>
</tr>
<% for (var i = 1; i < rows.length; i++) { %>
<tr class="tableclass">
<td><%= rows[i].email %></td>
<td> <select class="select">
<% if (rows[i].role == 'admin') { %>
<option selected value="admin">admin</option>
<option value='user'>user</option>
<% } else { %>
<option selected value="user">user</option>
<option value="admin">admin</option>
<% } %>
</select>
</tr>
<% } %>
</table>
<input type="submit" name="submit" value="submit" />
</form>
If I want to change some user's role I need to extract the data from table to JSON format for example in post request, how can I do this?
I tried to use request and cheerio
router.post('/saveRoles', function(req, res, next){
request.get('http://127.0.0.1:3000/adminOffice', function(err,
response, body, callback){
var $ = cheerio.load(body);
var result = $(".tableclass").map((i, element) => ({
email: $(element).find('td:nth-of-type(1)').text(),
role: $(element).find('.select option:selected').text()
})).get();
console.log(result[0].role);
database.connection.query("select email, role from users", function(err, rows, fields){
if(err) console.log(err);
for(var i = 1; i < rows.length; i++){
if(rows[i].role != result[i-1].role){
database.connection.query("update users set role = ? where email = ?", rows[i].role, rows[i].email, function(err, res){
if(err) console.log(err);
console.log("success");
});
} else {
console.log("not success");
}
}
});
});
res.redirect('/adminOffice');
});
but they works with new /adminOffice page and with initial values there.
For example there're 2 users in my table: {email: user1#user, role: user}, {email: user2#user, role: user}, I change role of 1st user to admin and press sumbit, request loads new adminOffice page where 1st user again has role user so post logs double not success and DB never changed.
Maybe I should use AJAX or smth else (new to NodeJS and JS)
Changed html code:
<form method="post" action="/saveRoles">
<% for (var i = 1; i < rows.length; i++) { %>
<div class="form-group">
<label for="changingRole"> <%= rows[i].email %></label>
<select name="role">
<% if (rows[i].role == 'admin') { %>
<option selected value='admin'>admin</option>
<option value="user">user</option>
<% } else { %>
<option selected value="user">user</option>
<option value="admin">admin</option>
<% } %>
</select>
</div>
<% } %>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
so I can easy now extract roles and work with them further
router.post('/saveRoles', urlencodedParser, function(req, res, next){
var roles = req.body;
database.connection.query("select email, role from users", function(err, rows, fields){
if(err) console.log(err);
for(var i = 1; i < rows.length; i++){
console.log(rows[i].role);
console.log(roles.role[i-1]);
if(rows[i].role != roles.role[i-1]){
database.connection.query("update users set role = ? where email = ?", [roles.role[i-1], rows[i].email],
function(err, res){
if(err) console.log(err);
console.log("success");
});
} else {
console.log("not changed");
}
}
});
res.redirect('/adminOffice');
});
Related
I have an code in NodeJS which stores data in collection specific to the user.
This the router to GET and POST the data from EJS form.
server.get('/changeaccounts', async (req, res) => {
try{
const accounts = await account.find({user: req.user.id}).lean()
res.render("backend/changeaccounts", {
name: req.user.name,
accounts
});
} catch(err) {
console.log(err)
}
})
server.post('/changeaccounts', async (req, res) => {
try{
req.body.user = req.user.id
await account.create(req.body)
res.redirect('/dashboard')
}catch(err) {
console.log(err)
}
})
This sends the data entered from the form to the collection specific to every logged in user(included in the attached image)
Here is the image for database
I have an forEach loop going in the EJS template
<% if (accounts) {%>
<table class = "striped">
<thead>
<tr>
<th>Account</th>
<th>Select Account</th>
</tr>
</thead>
<tbody>
<% accounts.forEach(accounts => { %>
<tr>
<td><%= accounts.title%></td>
<td><button type="submit" id="buttonforaccount" class = "btn btn-primary col-auto" >Use this account</button></td>
</tr>
<%});%>
</tbody>
</table>
<%} else {%>
<p>You have no accounts added</p>
<% } %>
The output is given in the second attached image.
This is the image for the table output
What I want to do is when the Button is clicked by the user, it fetches the title and password (as shown in first image) from the collection and is usable through my code as follows.
control.post('/like', (req, res, next) => {
let tags = req.body.likes;
let title = From the collection on button click //title here
let password = from the collection on button click //password here
iglike(title, password, tags);
next();
res.send(title);
res.send(password);
res.send(tags);
});
I want to pass data from MySQL database in datalist option. My application is written in express js using ejs view. I can't figure out how to pass database values to list in JavaScript and how to pass this list to ejs file.
add.js:
module.exports = {
addProductPage: (req, res) => {
let query = "SELECT shipper_names.Shipper_ID, shipper_names.Shipper_Name FROM shipper_names";
conn.query(query, (err, results) => {
if (err) {
return res.status(500).send(err);
}
res.render('add-product.ejs', {
title: "Add Product",
shipper_names: results[0],
message: ''
});
});
}
}
EJS file:
<!doctype html>
<html lang="en">
<div>
<a class="float-right" href="/" title="Home">Home</a>
</div>
<div class="contnainer">
<% if (message) {%>
<p class="text-container text-danger">
<%= message %>
</p>
<%}%>
<% if (shipper_names) {%>
<form class="add-player-form" action="" method="POST" enctype="multipart/form-data">
<div>
<input type="text" id="shippers_names" list="languageList" />
<!--your input textbox-->
<datalist id="languageList">
<option value=""> </option>
</datalist>
</div>
<button type="submit" class="btn">Add Product</button>
</form>
<% } else { %>
<p class="text center">Product Not Found. Go HereTo Add Product.</p>
<% } %>
</div>
</html>
module.exports = {
addProductPage: (req, res) => {
let query = "SELECT * from shipper_names"
conn.query(query, (err, results) => {
if (err) {
return res.status(500).send(err);
}
res.render('add-product.ejs', {
shipper_names: results
});
});
},
<div>
<input type="text" id="txtAutoComplete" list="names" />
<!--your input textbox-->
<datalist id="names">
<% shipper_names.forEach((shipper_names, index)=>{%>
<option id=<%= shipper_names.Shipper_ID%>>
<%= shipper_names.Shipper_Name%></option>
<%})%>
</datalist>
</div>
this is working
I have 2 drop down menus that are being populated using a query in SQL Server. Based on the selected items, I am loading a different ejs template. I have done this using the help of AJAX. However, I want to be able to load the data according to the selected criteria. For instance, if DD1 is selected as Andrew and DD2 as Date the table should load 7 columns based on those conditions.
AKA
SELECT * FROM exTable x WHERE x.Name = Andrew and x.Date = '4/22/2019
router.js
router.get('/', async (req, res) => {
try {
var name = await conn.query("SELECT DISTINCT pr.Name FROM WFS.PRTABLE pr WHERE pr.Functional_Group = 'Test'");
var dates = await conn.query('SELECT r.Date FROM WFS.Dates r');
res.render('index', {name : name , dates: dates});
} catch (err) {
res.status(500)
res.send(err.message)
}
});
router.post('/selection', async (req, res) =>{
try {
var name = await conn.query("SELECT DISTINCT pr.Name FROM WFS.PRTABLE pr WHERE pr.Group = 'Test'");
var dates = await conn.query('SELECT r.Date FROM WFS.Dates r');
var dateID = req.body.Dates;
var nameID = req.body.Names;
var tables = await conn.query("SELECT * FROM WFS.Views v WHERE v.Name = ? AND v.Date = ?", [ nameID , dateID ], function(err){
if(err) throw err;
res.render('selection', {tables: tables, name : name , dates: dates});
});
}
catch (err) {
res.status(500)
res.send(err.message)
}
});
index.ejs
<script>
$(document).ready(function(){
$('#date').on('change', function(event) {
var dates = $('#selections option:selected').val();
});
$('#name').on('change', function(event) {
var manVal = $('#selection option:selected').val();
alert(manVal);
});
$('#submitData').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/selection",
data: {dates : dates , manVal: manVal},
success: function() {
alert('success');
}
});
});
});
</script>
<form action="/selection" method="POST">
<select class="DateDD" id="date" name="Dates">
<% for(var n=0; n < dates.recordset.length; n++) { %>
<option><%= dates.recordset[n].Date%></option>
<% } %>
</select>
<select class="NameDD" id="name" name="Names">
<% for(var n=0; n < name.recordset.length; n++) { %>
<option><%= name.recordset[n].Name%></option>
<% } %>
</select>
<input type="submit" name="Submit" id="submitData" class="btn btn-primary" value="View Report" />
</form>
selection.ejs
CONTAINS THE SAME THING AS INDEX.EJS (besides the <script> tag) AND ...
<table class="table table-bordered table-condensed table-striped">
<% for(var n=0; n < tables.recordset.length; n++) { %>
<tr>
<td><%=tables.recordset[n].Name%></td>
<td><%=tables.recordset[n].Date%></td>
....
....
....
....
</tr>
<% } %>
</table>
This is the error I receive: Incorrect syntax near '?' after I hit the submit button.
I am trying to implement the update route into a poker site I am building. I have been able to get the players to appear on the show page but I would like to update the mongo DB from inTournament: "Yes" to inTournament: "No" when the Eliminate button is selected for that player. I have included my code below. Thank you, in advance, for any help with this.
======================= app.js UPDATE ROUTE=======================
app.get("/seating", function(req, res){
//Get all players from poker_DB
Seat.find({inTournament: "Yes"}, function(err, allseats){
if(err){
console.log(err);
} else {
shuffle(allseats);
res.render("seating", {seats: allseats});
}
});
});
//Update player's tournament status
app.put("/seating", function(req, res){
Seat.findByIdAndUpdate(req.params.id, req.params.inTournament, function(err, updatedStatus){
if(err) {
console.log(err);
} else {
res.send("Data Updated");
}
});
});
======================= SHOW PAGE=======================
<div class ="row text-left" style="display:flex; flex-wrap: wrap;">
<div class="col-md-4 table table-bordered">
<h3 class="text-center">Table 1</h3>
<ol>
<% var i = 1; %>
<% var j = 0; %>
<% seats.forEach(function(seat){ %>
<% if(seat.player && i < perTable1){ %>
<% console.log(perTable2); %>
<li><%= seats[j].player %>
<form action"/seating?_method=PUT" method="POST">
<button class="btn btn-sm btn-warning" type="Submit">Eliminate</button>
</form>
</li>
<% i++ %>
<% j++ %>
<% } else { %>
<% j++ %>
<% } %>
<% return j; %>
<% }); %>
</ol>
</div>
</div>
I am using elastic search in my application and everything works fine until you click the search result link which returns undefined. The problem I have is that the _source._id is returning undefined. So I cannot view the search result.
How can I pass the object id in /blog/article/<%= data[i]._source._id?
My code is below
router.js
router.post('/search', function(req, res, next) {
res.redirect('/search?q=' + req.body.q);
});
router.get('/search', function(req, res, next) {
if (req.query.q) {
Article.search({
query_string: { query: req.query.q}
}, function(err, results) {
results:
if (err) return next (err);
var data = results.hits.hits.map(function(hit) {
return hit;
});
res.render('main/search-result', {
query: req.query.q,
data: data
});
});
}
});
search-result.ejs
<% for (var i=0; i < data.length; i++) { %>
<div class="col-md-4">
<a href="/blog/article/<%= data[i]._source._id %>">
<div class="thumbnail">
<h3 id="data_title"><%= data[i]._source.title %></h3>
</div>
</div>
<% } %>
Finally resolved this issue by changing
<a href="/blog/article/<%= data[i]._source._id %>">
to
<a href="/blog/article/<%= data[i]._id %>">