I'm using a form to capture information from a list and save it to a new table on my database. When the restaurant name is more than one word, i.e. New York, it will ignore everything after the first word adding only the first word to the database. Is there a way to fix this?
View:
{{#allRestaurantsData}}
<div class="listing">
<form action="/restaurants" method="post">
<h2> {{restaurant.name}}
<input type="image" src="../wishlisticon.png" />
</h2>
<img id="image" src="{{restaurant.featured_image}}" width='500' height='300' alt="picture unavailable">
<ul>
<li>Address :{{ restaurant.location.address}}</li>
<li> {{restaurant.location.locality}}</li>
<li>{{restaurant.location.city}}</li>
<li>{{restaurant.location.zip}}</li>
</ul>
<div id="comments">
</div>
<input type="hidden" name="restaurant_id" value={{restaurant.id}}>
<input type="hidden" name="restaurant_name" value={{restaurant.name}}>
<input type="hidden" name="restaurant_city" value={{restaurant.location.city}}>
</form>
</div>
{{/allRestaurantsData}}
Controller:
router.post("/restaurants", restaurantsModel.create, (req, res, next) => {
console.log("Hitting /restaurants", res.locals.listitem);
});
Model:
restaurantsModel.create = (req, res, next) => {
console.log("from restaurants.Model", req.body);
db
.manyOrNone(
"INSERT INTO restaurants (res_id, name, city) VALUES ($1, $2, $3) RETURNING *;",
[
req.body.restaurant_id,
req.body.restaurant_name,
req.body.restaurant_city
]
)
After a lot of trial an error, I found the answer. I changed added quotation marks to the value inputs in the following two line.
<input type="hidden" name="restaurant_name" value="{{restaurant.name}}" >
<input type="hidden" name="restaurant_city" value="{{restaurant.location.city}}">
Related
I have created a blog site in NodeJS, EJS using mongodb. My problem is my posts show up from my database but I I want to make a change to it, it won't save.
app.js
app.post('/do-edit-post/:postId',(req, res) => {
const requestedPostId = req.params.postId;
Post.updateOne({ _id:requestedPostId }, {$set: {
title: req.body.title,
author:req.body.author,
content:req.body.content
}
}, function (err, result) {
if (err) {
console.log(err);
} else {
console.log("Post Updated successfully");
res.redirect("/admin");
}
});
});
In my editpostID.ejs:
<form class="" action="/do-edit-post" method="post">
<div class="form-group">
<label>Title</label>
<input class="form-control" hidden="<%= post._id %>">
<input class="form-control" text="text" name="postTitle" value="<%= title %>">
<label>Author</label>
<input class="form-control" text="text" name="postAuthor" value="<%= author %>">
<label>Post</label>
<!-- Text area matching the selector specified in the TinyMCE configuration -->
<textarea id="mytextarea" class="form-control" name="postBody" rows="5" cols="30" value=<%- content %>> </textarea>
</div>
<button class="btn btn-warning" type="submit" name="button">Save</button>
</form>
I even tried adding a hidden input field of ._id but it's not saving. What am I missing?
First of all you should add a input name on your hidden input
<form class="" action="/do-edit-post" method="post">
<div class="form-group">
<label>Title</label>
<input class="form-control" type="hidden" value="<%= _id %>" name="postId"> //<-- name added here also you should send the id on input value
<input class="form-control" text="text" name="postTitle" value="<%= title %>">
<label>Author</label>
<input class="form-control" text="text" name="postAuthor" value="<%= author %>">
<label>Post</label>
<!-- Text area matching the selector specified in the TinyMCE configuration -->
<textarea id="mytextarea" class="form-control" name="postBody" rows="5" cols="30" value=<%- content %>> </textarea>
</div>
<button class="btn btn-warning" type="submit" name="button">Save</button>
</form>
Then on node side you can get the id like this
app.post('/do-edit-post/:id',async (req, res) => {
const requestedPostId = req.body.postId; // <-- get the id from the form
await Post.findByIdAndUpdate(requestedPostId , {
title: req.body.title,
author:req.body.author,
content:req.body.content
}).catch(err => {
if (err){
console.log(err)
}else{
console.log("Post Updated successfully");
res.redirect("/admin");
}
})
});
I have got two things in form the first is add a password and the other is id which is no need to enter as it comes from the database directly when I click on add I got an error
Post method is
router.post('/', checkLogin, function (req, res, next) {
var user = localStorage.getItem('loginname');
var add_model = new pass_cat({
password: req.body.catename,
user_id: req.body.id
})
add_model.save(function (err, doc) {
if (err) throw err;
res.render('AddCategory', {
title: 'Password Management System',
user: user,
msg: 'Inserted Successfully'
})
})
});
And the ejs code for the form is
<form action="/add_category" id="EmployeeForm" class="form-horizontal" method="post" role="form">
<input type="hidden" name="id" value="<%= data%>" >
<div class="form-group">
<label for="Username" class="col-md-3 control-label">Add Category Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="catename" placeholder="Enter Password Category">
</div>
</div>
<div class="form-group">
<label for="User_id" class="col-md-3 control-label">User_id</label>
<div class="col-md-9">
<input type="text" class="form-control" name="userid" value="<%=data[0]._id%>" placeholder="Enter Password Category">
</div>
</div>
<input type="hidden" name="id" value="<%= data%>" >
there is no need of this line in the form, as data you are not setting anywhere, and its value is not defined.
I am trying to call a restful api created in expressjs from EJS form.
I tried looking on google and stackoverflow, and trying lots of different methods.
orders.ejs:
<ul class="orders">
<% for(var i=0; i<orders.length; i++) {%>
<ul class="order">
<p> coffee_id <span><%= orders[i].name %></span>
amount: <span><%= orders[i].amount %></span>
quantity <span><%= orders[i].quantity %></span> </p>
</ul>
<% } %>
</ul>
<div>
<form action="/orders" method="POST" action="orders/?_method=PUT">
<input type="text" placeholder="username" name="username">
<input type="text" placeholder="coffee name" name="name">
<input type="number" placeholder="amount" name="amount">
<input type="number" placeholder="quantity" name="quantity">
<button type="submit" id="order" >Submit</button>
</form>
</div>
nodejs.app.js:
app.post('/orders', (req, res) => { // falta o EJS
db.collection('orders').save(req.body, (err, result) => {
if (err) return console.log(err)
console.log(req.body);
res.render('orders.ejs', {
put: true
});
})
})
app.put('/orders/:coffeeid/:quantity', function(req, res) { ...
}
This code works fine individually calling them from Postman with the right parameters, but I need to call them both when I submit the EJS form.
app.get('/orders/:coffeeid',function(req, res) {
db.collection('orders').find({_id:req.params.coffeeid}).toArray, function(error,result){
if(!error && result && quantity){
return res.render('orders.ejs',{orders: result, coffeeid:result.coffeeid, quantity:'7'}); // <-- pass coffeeid to view
}
}
});
I need to read quantity also from the form and check for stock in the PUT, so for now I fixed it at '7'units, but now Cannot GET /orders
route for get orders :
app.get('/orders',function(req, res) {
// fetch all orders and display it to view
});
route for display edit page of order by coffeeid :
app.get('/orders/:coffeeid',function(req, res) {
var coffeeid= req.params.coffeeid;
db.collection('orders').find({_id:coffeeid}).toArray,function(error,result){
if(!error && result){
return res.render('orders.ejs',{orders:result,coffeeid:result.coffeeid, quantity:'7'});
}
});
});
form :
<form action="/orders/<%=coffeeid%>" method="POST">
<input name="_method" type="hidden" value="PUT">
<input type="text" placeholder="username" name="username">
<input type="text" placeholder="coffee name" name="name">
<input type="number" placeholder="amount" name="amount" value="">
<input type="number" placeholder="quantity" name="quantity" value="<%=quantity%>">
<button type="submit" id="order" >Submit</button>
</form>
to update information route will be :
app.put('/orders/:coffeeid', function(req, res) {
var coffeeid= req.params.coffeeid;
var quantity= req.body.quantity;
// save to database
}
I have file views/user/index.ejs
<form action="" method="POST>
<label>Username: </label>
<input type="text" class="form-control" value="<%= req.param('username') %>" name="username">
<input type="Submit" value="Submit">
</form>
Content of api/controllers/UserController.js
module.exports = {
index: function (req, res) {
sails.log(req.param('username'));
// Result: invest
}
}
Although the log print "invest", but the content of input is "undefined". I think that the array of requested parameters had not been kept.
Can anyone help me solve it? I will donate 2 eggs ;)
You can use this to pass variables to your view:
module.exports = {
index: function (req, res) {
return res.view("user/index", {username: req.param('username')});
}
}
In your view:
<input type="text" class="form-control" value="<%= username %>" name="username">
I'm using Node/Express (most recent production versions)
I have a form where I collect new account info. The user can add a username, etc.
In the view handler, I check a mongodb database to see if the username is unique. If it is not, I generate a message and reload the original view. Since the original request was a post, all of the data the user posted is in req.body. I would like to add the data the user submitted on the response. I could do it by specifically adding each value to the response. But isn't there an easier way to add all the request data back to the response? And is there a way to render that in the view (i'm using ejs) I tried res.send(JSON) coupled with ejs variables. Doing so generates errors saying the variables aren't available.
Here's my function (ignore the users.createUser(req) - it's not finished yet):
createAccount: function(req, res, next){
users.createUser(req);
res.render('create_account', {
layout: 'secure_layout',
title: 'Create Account',
givenName: req.body.givenName,
username: req.body.username,
familyName: req.body.familyName
});
},
And here's my view:
<form action="/createAccount" method="post">
<div>
<label>First Name:</label>
<input type="text" name="givenName" value="<%= givenName %>"/><br/>
</div>
<div>
<label>Last Name:</label>
<input type="text" name="familyName" value="<%= familyName %>"/><br/>
</div>
<div>
<label>Username:</label>
<input type="text" name="username" value="<%= username %>"/><br/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div>
<input type="submit" value="Submit"/>
</div>
</form>
It seems overly complex to have to add each of the values. I tried {body: req.body} but values were never added to the view.
I'm not quite sure what you're after, but if you want to render an ejs view with data that was on the request body, you would do something along these lines:
app.post('/foo', function(req, res, next) {
res.render('view', {body: req.body});
});
view.ejs:
<ul>
<% for(var key in body) { %>
<li><%= key %>: <%= body[key] %></li>
<% } %>
</ul>