Is there a way to use EJS variables in HTML inputs? - html

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.

Related

react js form getting submitted twice

I have below code which calls save form
<div className="col-md-4">
<button onClick={saveCredit} className="btn btn-success">
Submit
</button>
I have onclick handler function as
const saveCredit = () =>{
//validate form
// call api to save form attributes
CreditTransactionDataService.create(data)
.then(response => {
setSubmitted(true);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
after successful save , I will show successful message as below.
{submitted ? (
<div>
<h4>You submitted successfully!</h4>
<button className="btn btn-success mr-2" onClick={newCreditTransaction}>
Add
</button><Link style={{ fontWeight: 'bold' }} className="btn btn-warning" to={"/creditTransactionList"}>
return to List
</Link>
</div>
)
but the problem is, my form is getting submitted twice, and creating duplicate records with same values.... couple of save options, i restricted with unique key column at database level, but few tables still need to handled at code level..
I´m unable to reproduce it in codepen, but one solution a little bit hacky could be check in the method if it is submitted already
const saveCredit = {
//Check if it is submitted
if(!submitted){
//validate form
// call api to save form attributes
CreditTransactionDataService.create(data)
.then(response => {
setSubmitted(true);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
}
This may not be the best but could do the job
Also a thing I did notice is that your saveCredit function not look like a function.
Why not declare as an arrow function? Like:
const saveCredit = () => { //Your code }
Your button doesn't need onClick event handler if it's responsible for submitting a certain form. You should add type="submit" to button and onSubmit to form tag itself.
You should go for this approach to handle submitting correctly (clicking of the button or hitting enter by the user are covered).

How to send html form data to another web server via a button click

I have two web servers. One running my front-end (example.com), one running my back-end (api.example.com).
On my front-end (example.com) I have this code which is a simple html website that has a form, with an input field and a button. When I click the button I'd like to get that data and send it to the back-end (api.example.com). For example, I put 'nathan' in the username field of the front end and click the button. I want it to send me to api.example.com/sendcode?username=nathan
I currently have this code, but the button is keeping me on the same website, instead of doing to a completely different url:
<form class="login100-form validate-form flex-sb flex-w" action="api.example.com" method="POST">
<span class="login100-form-title p-b-51">
Request for a code
</span>
<div class="wrap-input100 validate-input m-b-16" data-validate = "Username is required">
<input class="input100" type="text" name="username" placeholder="Username">
<span class="focus-input100"></span>
</div>
<div class="container-login100-form-btn m-t-17">
<button class="login100-form-btn">
Send code
</button>
</div>
<div class="flex-sb-m w-full p-t-3 p-b-24">
<div class="contact100-form-checkbox">
</div>
</div>
</form>
With this code it's sending me to 'example.com/api.example.com?username=nathan' How would I fix this, would like to keep the two completely different?
You need a fully qualified URL with protocol - preferably https, as in action="https://api.example.com/sendcode"
Please search for AJAX and your server process. Alternatively use fetch
const username = document.querySelector("[name= username]").value;
fetch('https://api.example.com/sendcode?username='+encodeURIComponent(username))
.then(response => response.json())
.then(data => console.log(data));
To use Ajax, you need to grab the submit event
Here I use jQuery for speed of coding an example, just include <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> in the page to use it
$(".login100-form").on("submit", function(e) {
e.preventDefault(); // stop submit
$.post('https://api.example.com/sendcode',
{ data : $(this).serialize() }, // the form content in key=value format
function(response) {
console.log(response)
})
})
Change your form action to include http:// e.g.
<form class="login100-form validate-form flex-sb flex-w" action="http://api.example.com" method="POST">
There could be numerous methods depending upon scenarios but simplest of all which might expose data in querystring is sending a post request on button click through a simple javascript method.

NodeJS Express HTML hidden input value showing only first word

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!

A form with POST method submitting a GET

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?

How I use the data from Angular on Node JS? And how can I make a page load the information about a certain "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.