I tried to delete multiple items from database using check box using node.js.But if any one of the check box is true everything is true.How to get this?
here the checkbox value for each item is not getting passed.
how to solve this.
router.post('/del', function (req, res, next) {
mongo.connect(url, function (err, db) {
assert.equal(null, err);
var cursor = db.collection('log').find();
cursor.forEach(function (doc, err) {
var id2 = Boolean(req.body.chk);
db.collection('log').findAndModify({ "option": id2 }, function (err, result) {
if (result) {
assert.equal(null, err);
console.log('Item updated');
resultArray4.push(id2);
console.log(resultArray4);
var id3 = id2;
id2 = null;
db.collection('log').deleteMany({ "option": id3 }, function (err, result) {
assert.equal(null, err);
console.log('Item deleted');
});
} else {
res.render('check');
}
});
});
}); res.render('check');
resultArray4.length = 0;
id2 = id3 = null; count = 0;
});
Handlebars code ....here the checkbox value for each item is not getting passed.
how to solve this.
<div class="deletedd">
<table class="table-table-bodered" border="auto" style="solid">
<th>Title</th>
<th>Content</th>
<th>Author</th><br><br>
<th>Select</th>
<div>
{{#each items }}
<tr>
<article class="item">
<td>{{ this.name }}</td>
<td>{{ this.number }}</td>
<td>{{ this.address }}</td>
<td>
<form action="/checkss/del" method="post"><input type="checkbox" name="chk"></td>
</article>
</tr>
{{/each}}
</div>
</table>
</div>
<button type="submit">delete</button>
</form>
Related
This is the route code:
router.get('/compose/:ID', function(req, res, next) {
var random = Math.floor((Math.random() * 1000000) + 1);
console.log("random = " + random);
res.render('compose', { random: random, Id:req.params.ID });
})
.post(function(req, res, next) {
var to = '917985754084';
var from = 'GrumpyText';
var text = req.body.OTP;
console.log(text);
nexmo.message.sendSms(from, to, text, function(err,success){
if(success)
console.log("SMS sent successfully!");
else {
console.log("error");
}
});
});
This is the handlebar code:
<main role="main" class="container">
<div class="jumbotron">
<h1>List of Contacts</h1>
<table class="table table-striped">
<thead>
<tr>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<form method="post" enctype="multipart/form-data">
<tr>
<td><input type="text" name="OTP" class="form-control" value="Hi. Your OTP is : {{random}}"></td>
<td></td>
</tr>
<tr>
<td><button type="submit" class="btn btn-lg btn-primary btn-block">Submit</button>
</td>
</tr>
</form>
</tbody>
</table>
</div>
</main>
Its coming to the route but the console is not printing the 'text'. aka console.log(text) means req.body.OTP is not printing anything. Earlier it was printing undefined.
Could you please rectify where it is stucking perhaps?
The issue you are hitting is body-parser doesn't handle multipart/form-data.
There are several options, but one of those is multer.
\* add these for multi-part*\
var multer = require('multer')
var upload = multer();
\* other code *\
router
.get('/compose/:ID', function (req, res, next) {
var random = Math.floor(Math.random() * 1000000 + 1);
console.log('random = ' + random);
res.render('compose', { random: random, Id: req.params.ID });
})
.post('/compose/:ID', upload.none(), function (req, res, next) {
var to = '917985754084';
var from = 'GrumpyText';
var text = req.body.OTP;
nexmo.message.sendSms(from, to, text, function (err, success) {
if (success) console.log('SMS sent successfully!');
else {
console.log('error');
}
});
});
The Express version is 4.16.4
I downloaded a file :
... <i class="fa fa-download"></i>
router.get("/downloadfacturemaintenance/:facture", function (req, res) {
var facture = req.params.facture;
res.download(path.join(__dirname, '../config/uploads/facture_maintenance/'+facture), "facture.png", function (err) {
console.log(err);
});
});
At runtime the download starts. But the filename in the download is the filename in the first parameter of res.download ; although I defined an alternate name in the second parameter. But this second parameter is not considered ! So why ?
edit :
here is code :
router.post("/maintenancereparation", function (req, res) {
async.parallel({
types_vehicule: function (cb_types_vehicule) {
connexion.query("select type_vehicule_id, type_vehicule_lib from " + utils.getPrefixNomTables() + "type_vehicule order by type_vehicule_id", function (err, rows) {
if (err)
throw err;
cb_types_vehicule(null, rows);
});
},
maintenances: function (cb_maintenance) {
connexion.query("select m.maintenance_id, m.maintenance_date_fin, v.immatriculation, m.maintenance_terminee, m.maintenance_facture from " + utils.getPrefixNomTables() + "maintenance m join " + utils.getPrefixNomTables() + "vehicule v on m.vehicule_id = v.vehicule_id order by m.maintenance_terminee, m.maintenance_date_fin", function (err, rows) {
if (err)
throw err;
cb_maintenance(null, rows);
});
}
}, function (err, results) {
res.render("maintenancereparation", { "types_vehicule": results.types_vehicule, "maintenances_new": results.maintenances });
});
});
<!DOCTYPE html>
<html lang="fr">
<head>
<style>
.center {
text-align: center;
}
</style>
</head>
<body>
<form id="frm" style="margin-top: 10px;">
<fieldset>
<legend>Maintenance / Réparation</legend>
<div class="row form-group col-sm-12">
<div class="radio">
<label><input type="radio" name="type_action" id="action_maintenance" /> Maintenance</label>
</div>
<div class="radio">
<label><input type="radio" name="type_action" id="action_reparation" /> Demande de réparation</label>
</div>
</div>
<div id="div_maintenance">
<table class="table" id="list_maintenance">
<thead>
<tr>
<th>Véhicule</th>
<th>Date fin maintenance</th>
<th style="background: #FFDD00 !important; font-size: 13px !important;">Actions</th>
<th>Closed</th>
<th>facture</th>
</tr>
</thead>
<tbody>
<% maintenances_new.forEach(function(maintenance){ %>
<tr>
<td><%= maintenance.immatriculation %></td>
<td><%= maintenance.maintenance_date_fin %></td>
<td><%= maintenance.maintenance_id %></td>
<td><%= maintenance.maintenance_terminee %></td>
<td><%= maintenance.maintenance_facture %></td>
</tr>
<% }) %>
</tbody>
</table>
</div>
<div id="div_repair">
<div class="row form-group col-sm-12">
<label class="col-sm-1">Type véhicule</label>
<select id="type_vehicule" name="type_vehicule">
<option value="">-- Sélectionner --</option>
<% types_vehicule.forEach(function(type_vehicule){ %>
<option value="<%= type_vehicule.type_vehicule_id %>"><%= type_vehicule.type_vehicule_lib %></option>
<% }) %>
</select>
</div>
</div>
</fieldset>
</form>
</body>
</html>
<script>
$(document).ready(function () {
$(":radio[name='type_action']").on("change", function () {
if ($("#action_maintenance").is(":checked")) {
$("#div_repair").hide();
$("#div_maintenance").show();
} else {
$("#div_maintenance").hide();
$("#div_repair").show();
}
});
$("#action_maintenance").prop("checked", true);
$(":radio[name='type_action']").change();
var list = $("#list_maintenance").DataTable({
"language": {
"loadingRecords": "Veuillez patienter...",
"processing": "Veuillez patienter...",
"zeroRecords": "Aucun résultat",
"emptyTable": "Aucun résultat"
},
"columns": [
{ "data": 0, className: "center" },
{ "data": 1, className: "center" }
],
"columnDefs": [
{
"targets": 1,
"render": function (data, type, row) {
return ( data == "" ? "" : (new Date(data)).toLocaleDateString() );
}
},
{
targets: [2],
orderable: false,
searchable: false,
render: function (data, type, row) {
if (row[3] == 1) {
var facture = row[4];
var fichier = facture.substring(facture.lastIndexOf("/") + 1);
var ext = fichier.substring(fichier.lastIndexOf("."));
//fichier = fichier.substring(0, fichier.indexOf("_"));
var url = "/track/vehicule/downloadfacturemaintenance/"+fichier;
return '<i class="fa fa-download"></i>';
}
else
return '<i class="fa fa-flag"></i>';
}
},
{
targets: [3,4],
orderable: false,
searchable: false,
visible:false
}
]
});
list.on("click", "a[data-id]", function () {
var pk = $(this).data("id"), vehicule = $(this).data("vehicule");
$("#george_content").load("/track/vehicule/clotureMaintenance/" + pk + "/" + vehicule);
});
});
</script>
router.get("/downloadfacturemaintenance/:facture", function (req, res) {
var facture = req.params.facture;
var fichier = facture.substring(facture.lastIndexOf("/") + 1);
var ext = fichier.substring(fichier.lastIndexOf("."));
fichier = fichier.substring(0, fichier.indexOf("_"));
res.download(path.join(__dirname, '../config/uploads/facture_maintenance/'+facture), "facture.png", function (err) {
console.log(err);
});
});
This code is working for me
app.get('/download', function(req, res){
const file = `${__dirname}/demo.jpg`;
//res.attachment()
res.download(file,"DEMO.jpg"); // Set disposition and send it.
});
If it's not working probably due to caching, clear browser cache, It should work then. I was also facing the same problem when I tried replicating the issue and it turned out there is nothing wrong with code. Then I opened a browser in incognito mode, it worked as expected.
Check response header Content-Disposition in both cases:
When you don't pass filename as the second arg to res.download:
Passing filename as the second argument:
Tested in
I tried replicating this problem with this code: https://github.com/alexkubica/stackoverflow-example-express-download-with-filename-parameter
I suspected at first that maybe it has something to do with you traversing up the directories but it worked just fine.
Is it possible for you to upload your code so we can debug it?
I'll try looking into it and update this answer once I come with a solution.
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');
});
I am new to node.js. I am created small example, now I want to delete multiple rows based on checkbox condition. I have one table of checkboxes as last column. I want delete checked checkbox rows when click on button.
Jade code is
<section class="get">
<h3>Get Data</h3>
LOAD DATA
<div>
<table>
{{# each items }}
<article class="item">
<tr>
<td>{{ this.title }}</td>
<td>{{ this.content }}</td>
<td>{{ this.author }}</td>
<td>{{ this._id }}</td>
<form action="/check" method="post">
<td><input type="checkbox" id="chk" name="chk" ></td>
</article>
</tr>
{{/each}}
<button>check</button>
</form>
</table>
</td>
</section>
Back end code is
router.get('/get-data', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db) {
assert.equal(null, err);
var cursor = db.collection('user-data').find();
cursor.forEach(function(doc, err) {
assert.equal(null, err);
resultArray.push(doc);
}, function() {
db.close();
res.render('index', {items: resultArray});
});
});
});`
router.post('/check', function(req, res, next) {
// var id = req.body.id;
console.log("check value");
console.log(req.body.chk);
req.body.chk=Boolean(req.body.chk);
for(i=0; i<req.body.chk;i++){
if(req.body.chk==true){
res.redirect('/');
}
else{
res.send("checkbox is not checked");
}
}
});
Hi,
I'm trying to get value from mongoose and populate textbox with it. So basically when I click Edit button I would like the name of the department appear in Department name textbox. I tried multiple things but failed. ($('#departmentName').val(department.name) for example) How can I do it properly? Thank you.
my department handlebar
<h2>Departments List</h2>
<div class="row">
<div class="col-lg-12">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<form method="POST" action="/departments/create_department">
<td><input class="form-control" type="text" placeholder="Department Name" name="departmentName" id="departmentName"></td>
<td><button class="btn btn-primary" type="sumit">Add Department</button></td>
</form>
<td><button class="btn btn-info">Update</button></td>
<td><button class="btn btn-info">Clear</button></td>
</tr>
{{#each departments}}
<tr>
<form method="POST" action="/departments/remove_department/{{_id}}?_method=DELETE">
<td>{{name}}</td>
<td><button class="btn btn-danger" type="submit">Remove</button></td>
</form>
<form method="GET" action="/departments/edit_department/{{_id}}?">
<td><button class="btn btn-warning" value={{id}} type="submit">Edit</button></td>
</form>
</tr>
{{/each}}
</tbody>
</table>
</div>
</div>
my department controller
var express = require('express');
var router = express.Router();
var passport = require('passport');
var mongoose = require('mongoose');
var Departments = require('../models/department');
var User = require('../models/user');
// List of departments
router.get('/add_department', userAuthenticated, function(req, res, next) {
Departments.find(function(err, departments) {
if (err) {
throw err;
}
res.render('add_department', {title:'Add New Department', departments: departments, name: departments.name, id: departments._id})
})
});
// Edit department
router.get('/edit_department/:id', userAuthenticated, function(req, res, next) {
var departmentName = "";
Departments.findById(req.params.id).exec(function(err, department) {
if (err) {
throw err;
} else {
$('#departmentName').val(department.name);
res.redirect('/departments/add_department');
}
})
});
You could try changing the input field in handlebars to display the value you queried from mongoose
change this
<td><input class="form-control" type="text" placeholder="Department Name" name="departmentName" id="departmentName"></td>
to this
<td><input class="form-control" type="text" value={{name}} name="departmentName" id="departmentName"></td>
Then take this out of the routes
$('#departmentName').val(department.name);
UPDATE:
So something like this
// List of departments
router.get('/add_department', userAuthenticated, function(req, res, next) {
// grab the deparment from the req
var departmentFromEdit ="";
if(req.query.dn){
departmentFromEdit = req.query.dn;
}
Departments.find(function(err, departments) {
if (err) {
throw err;
}
res.render('add_department', {title:'Add New Department', departments: departments, name: departments.name, id: departments._id})
})});
// Edit department
router.get('/edit_department/:id', userAuthenticated, function(req, res, next) {
var departmentName = "";
Departments.findById(req.params.id).exec(function(err, department) {
if (err) {
throw err;
} else {
departmentName = encodeURI(department.name);
// dn for departmentName or defaultName
res.redirect('/departments/add_department?dn=' + departmentName);
}
})});