I have a node js app which uses EJS as the template engine. On several pages I use hidden inputs and access their values using req.body. I've setup my body parser in express and everything works great. However, it seems as though any hidden inputs that have a value that is more than one word only display the first word.
So for example my hidden input with name = "eventname" has value: "Sample hidden text". When I do req.body.eventname in my express route I get "Sample". To test I changed the value of my hidden input to "Sample_hidden_text" and in that case req.body.eventname comes through as "Sample_hidden_text". Do hidden inputs not allow spaces in the value?
Below is sample code. The value of event.name from the console log in page.ejs gives the correct value of "Sample hidden text". However, the console log in the post route gives "Sample".
Page.ejs
<form action="/addnewresult" method="POST">
<% console.log("the value of event.name hidden field", event.name) %>
<input type="hidden" name="eventname" value=<%= event.name %>>
<button type="submit" name="submit" class="btn">Submit</button>
</form>
App.js
var express = require("express"),
bodyParser = require("body-parser")
var app = express();
app.post("/addnewresult", function(req,res){
console.log("this is req.body in the post call: ", req.body);
DBhandler.CreateResult(req,res,function(callback){
//do some stuff here
});
});
This is just summary coming from Andrew Myers in the comment.
It is needed to use quotations -> "<%= event.name %>" instead of just <%= event.name %> to get the whole text displayed and not only the first word.
Thank Andrew Myers, it helped me also!
Related
I am trying use a check box to send all selected users to a new page and am wondering how this could be done (using mongodb to store information) My existing code is as follows,
first I render the page
router.get("/admin", ensureAuthenticated,(req, res) => {
User.find()
.then(user => {
res.render("admin", {
user: user,
});
})
});
For all of the users the website has I create a check box, and all selected users should get sent to a new page
<% for (i in user) { %>
<form action="/admin" method="POST">
<label for="checkbox"><%=user[i].name%></label>
<input type="checkbox" id="user" name="user">
</form>
<% } %>
<button type="submit">View Profile</button>
however when I console log it says that user info is undefined.
router.post("/admin", (req, res) => {
profile = req.body.name
console.log(`user info: ${profile}`)
res.redirect("/admin/userprofile")
router.get("/admin/userProfile", ensureAuthenticated,(req, res) => {
res.render("admin_user_profile", {
user: profile
})
});
})
any help will be greatly appreciated, thanks
Your page contains one <form> element per user but only one submit button overall. Either include the submit button in the <form>, but then you can only submit one of the users. Or move the <form> and </form> outside the for loop (and </form> after the submit button) and give every <input> a unique name, for example,
<input type="checkbox" id="<%=user[i].name%>" name="<%=user[i].name%>">
Then you can submit all checkboxes at once.
Next, your server-side code refers to req.body.name, where should that come from? req.body should contain one entry per user name, with the names of your <input> elements. And req.body.firstusername === "on" if the corresponding checkbox was selected.
In other words, you should get an object like
req.body = {
"firstusername": "on",
"thirdusername": "on"
}
if the first and third usernames are selected and the second is not selected.
This is the strangest problem i ever had, this is the view (in jade):
extends layout
block content
h1 Edit chatroom!!
form(method="POST")
fieldset.form-group
label(for="name") Name:
input.form-control(name="name", type="text", placeholder="Enter a name" value="#{room.name}")
small.text-muted Give your chatroom a meaningful name for people to refer to it.
button.btn.btn-primary(type="submit") Save chatroom
a.btn.btn-default(href="/admin/rooms") Cancel
this is the form source from the page source code returned to the browser :
<form method="POST">
<fieldset class="form-group"><label for="name">Name:</label><input name="name" type="text" placeholder="Enter a name" value="independents" class="form-control"><small class="text-muted">Give your chatroom a meaningful name for people to refer to it.</small></fieldset>
<button type="submit" class="btn btn-primary">Save chatroom</button>Cancel
</form>
when i press the "Save chatroom" button i get this error message on the web page :
Cannot GET /admin/rooms/edit/
this express router is supposed to handel the form submission
router.route('/rooms/edit/:id')
.all(function(req, res, next) {
var roomid = req.params.id;
var room = _.find(rooms, r => r.id == roomid);
if (!room) {
res.sendStatus(404);
return;
}
res.locals.room = room;
next();
}).get(function(req, res) {
res.render('edit');
}).post(function(req, res) {
res.locals.room.name = req.body.name;
//res.redirect(req.baseUrl + '/rooms'); or we can also
res.redirect('./'); // but this is not good because if we had http://localhost:3000/admin/rooms/add/ it will take us to /add
});
the whole code for this small express app(two js files) exist in this previous question i wrote.
In your route defintion you have
if (!room) {
res.sendStatus(404);
return;
}
And it looks like in your code, you're not submitting any request to a URL that has an ID, so it's returning 404 just like you told it to.
Unless you're on a URL that does have an ID. What does the URL look like on the page this is on?
I am trying to POST some values using my HTML form to a node JS method. Thereafter, I need to send the return result back from NODE JS and display it in the HTML page.
I am also using EJS to send back the values to the form. However, the result doesn't get displayed.
Basically, After the user clicks on the submit button on the HTML form, values should be passed to Node Js processed and send back a result Success or failed to the HTML doc where it'll display.
My code is as follows:
HTML CODE:
<form id="form-register" action="http://localhost:8089/ttt"" method="post" enctype="multipart/form-data">
<input type="logintext" value="" name="nam" class="nameC" id="mc" >
<input type="submit" name="subscribe" id="mc-submit-number">
<label >REEEEE <%= titles %></label>
</form>
NODE JS CODE:
app.post('/ttt', function (req,res){
loginProvider.signUp(params, function(err, data) {
if (err) {
res.render('index',{title: 'HOME',titles:err.stack
});
res.send('WHATTT');
}
else {
console.log('Result ' + data); // successful response
res.render('index',{title: 'HOME',titles:'SUCCESS'
});
res.end('xzxzxzxzxzx');
}
});
}
You could (or rather have to) use AJAX.
Then you can manually send your form parameters via post request to your Node server and return a response object with either an error or a success message.
The reason your code isn't working is because you have already loaded the DOM of the HTML page and when you are making that request the only way for EJS to work is if you reload the page since EJS just goes through your file and string replaces
My best solution is to have a normal AJAX call to your '/ttt' and have the Node.js do a 'res.send("SUCCESS");' and in your html you can set that label or any part of your document page to "SUCCESS"
With JQuery
$.post("/ttt", function(data, status){
$("#yourLabel").text(data);
});
I'm working on a project that I need from login, to compare the information at the form with the database. And later, after doing the validation, I need to load the information of a login in another page (I have no idea how).
(I tried to find some tutorials, but all of them use Express, that I'm not allowed to)
Now my code:
HTML (I think this part is OK, cause I could save the information in $scope.u)
<form ng-controller = "login" ng-submit="submit(user)">
<label>Login:</label>
<input type="text" ng-model="user.login" required>
<label>Senha:</label>
<input type="password" ng-model="user.pwd" required>
<label><input type="checkbox"> Lembre-me</label>
<button type="submit" class="btn btn-default">Login</button>
<p>{{user.login}}</p>
<p>{{user.pwd}}</p>
<p>LOGIN:{{user.login}}</p>
<p>SENHA:{{user.pwd}}</p>
</form>
Angular (I'm not sure if I understood the idea of $http.post, so I don't know if I can send the info of $scope.u to Nodejs)
app.controller('login',function($scope,$http){
$scope.u = {};
$scope.submit = function(user) {
$scope.u = angular.copy(user);
console.log($scope.u);
};
$http.post('/servico/login', $scope.u).success(function(data, status) {
console.log('Data posted successfully');
});
});
Node (If I could use the information of $scope.u, my problem would be finished there, but I don't know how I can load the information in another page)
The button Login should compare the values from the form and them, maybe, use to send to the other page.
function login(request,response){
var queryString = 'SELECT uLogin,uSenha FROM usuarios';
connection.query(queryString,function(err,rows){
});
}
I hope I've been clear with my doubt.
Thanks for your help.
I've the problem that I want to use a payment system for my website for which I need to setup a system by which users get redirected to a url. This url needs to contain their own username on the location of the text [USER_ID]. The problem is that the url is built up like: &uid=[USER_ID]&widget=m2_1 How can it get the [USER_ID] to change to exactly the same thing the user entered in a form before:
<form>
User: <input type="text" name="url1" id="url1" value=""><br>
<input type="submit" name="submit" value="Goto URL" onclick="redirect()">
</form>
And use the text the user submitted in the form box to get it on the place of [USER_ID]?
This approach uses jquery's val() to retrieve the value from the form input, then it concatenates it to the url. I hope you are doing some sort of user validation...
function redirect()
{
...
var userId = $("#url1").val();
var url = "redirect" + "&uid=" + userId + "&widget=" + widget;
...
}
In the redirect function that you are using, you can extract the data of the input box and redirect the user as
window.location = yoursite.com/yourpage.php?user_id=getElementById('url1').value;
If you attach an action attribute to the form tag say : action='submit.php', and also attach form tag method='post'. Also, add a then in the file 'submit.php' you would use the following code (indexed by the name attribute of the input tag). The last line is how to do a redirect in php.
<?php
//submit.php
$root = 'www.foo.bar/';
$user = $_POST['user'];
$url= $root.'&uid=[$user]&widget=m2_1';
header('Location: $url');
?>
checkout:
http://myphpform.com/php-form-tutorial.php
also, if you prefer to use javascript or jQuery you can use ajax to post to the server and get the response.