Using POST to sign up in a HTML file - javascript

I'm currently working on a project for school. I am building both a backend and a frontend application. I have the POST working on the backend and i've tested it with postman and it posts and saves it in MongoDB. How would I get the post working if its on a browser? I have a form with firstname, lastname, email, and password. How do I post on the browser? Is it possible to post on live server?
I tried hosting it on heroku and it didn't work. I tried hosting on react but it works but I would rather do it on liveserver if its possible.
here is my html file for registering.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Register</title>
<style>
html{
background-color:hsl(60, 20%, 80%);
}
input[type=text],
input[type=password] {
width: 100%;
padding: 15px;
border: black 1.5px solid;
background: #f1f1f1;
}
input[type=text]:focus,
input[type=password]:focus {
background-color: #ddd;
outline: none;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.7;
}
button:hover {
opacity: 1;
}
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
.cancelbtn,
.signupbtn {
float: left;
width: 50%;
}
.clearfix::after {
content: "";
clear: both;
display: table;
}
</style>
</head>
<body>
<form>
<h1>Sign Up</h1>
<p>Please fill in this form to create your accout.</p>
<label for="firstname"><b>First Name</b></label>
<input type="text" placeholder="Enter First Name" name="firstname" required>
<label for="lastname"><b>Last Name</b></label>
<input type="text" placeholder="Enter Last Name" name="lastname" required>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</form>
</body>
</html>
here is my post method for the back end.
router.post('/', sanitizeBody, async (req, res) => {
console.log(req.sanitizeBody);
let password = await bcrypt.hash(req.body.password, saltrounds)
new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
password,
email: req.body.email,
isStaff: req.body.isStaff
}).save().then(result => {
res.status(201).send(result);
}).catch(err => {
res.send(err);
})
})
I expect to post on the html page rather than posting it on postman. I would like it to post on the index.html live server when I hit submit.

Related

How do I check two fields for identity using an external script like "signup.js"?

I work with Electron.
I have three files in my project.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/styles.css">
<script src="../js/preload.js"></script>
<script src="../js/signup.js"></script>
</head>
<body>
<form action="" onsubmit="return validate()">
<label for="email"><b>Почта</b></label>
<input type="text" placeholder="Введите почту..." name="email" required>
<label for="psw"><b>Пароль</b></label>
<input type="password" placeholder="Введите пароль..." id="psw" required>
<label for="psw-repeat"><b>Подтверждение пароля</b></label>
<input type="password" placeholder="Повторите пароль..." id="psw-repeat" required>
<hr>
<p id = "terms">Создавая аккаунт, вы соглашаетесь с нашими условиями пользования и приватности.</p>
<button type="submit" class = registerbtn>Зарегистрироваться</button>
</form>
</body>
</html>
styles.css
#import url('https://fonts.googleapis.com/css2?family=Comfortaa:wght#300&display=swap');
#import url('https://fonts.googleapis.com/css2?family=Raleway&display=swap');
body {
font-family: 'Raleway', sans-serif;
}
.sign_up {
padding: 16px;
}
input[type=text],
input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
font-family: 'Raleway', sans-serif;
}
hr
{
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
.registerbtn {
background-color: darkcyan;
color: white;
padding: 16px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
.registerbtn:hover {
opacity: 1;
}
a {
color: dodgerblue;
}
#warning {
color: crimson;
}
signup.js
function validate()
{
var password = document.getElementById(psw).value;
var password_repeat = document.getElementById(psw-repeat).value
if(password != password_repeat)
{
document.getElementById(psw).insertAdjacentHTML("afterend", "<p id = \"warning\">Пароли не совпадают!</p>")
}
}
The project itself is written in Russian. I want to use the file signup.js to check the identity of the fields "psw" and "psw-repeat", but when the program runs, nothing happens. As for the content of the fields, they are emptied when the button is clicked.
The onsubmit value should only have method call, not with "return".
So, I suggest you to use something like this:
onsubmit="validate()"
Documentation
Also, the submit button have issue with "class" css, it should look like this:
<button type="submit" class="register btn">Зарегистрироваться</button>

window.location.href is not redirecting html page

I am trying to build a form and do some validation using JS. On success I want to redirect it to some other page in the same directory. While running window.location.href over console it is working...but while submitting form, it is not working.
Can someone please help me in this.
My code is:
<html>
<head>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
button:hover {
opacity: 0.8;
}
.container {
padding: 16px;
width: 400px;
align-self: center;
}
span.psw {
padding-top: 16px;
}
</style>
<title>Login Page</title>
</head>
<body style="text-align: center;">
<h2 style="text-align: center;">The Mega Cart</h2>
<form name=loginForm onsubmit="login()" style="display: inline-block;">
<div class="container" style="text-align: center;">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit">Login</button>
</div>
<span class="psw">New user Sign up here. Sign Up</span>
</div>
</form>
</body>
<script>
function login() {
let uname = document.forms["loginForm"]["uname"].value;
let pwd = document.forms["loginForm"]["psw"].value;
window.location.href="main.html";
return false;
}
</script>
</html>
I have already checked that this login function is called.
When you click on the form submit button it call the function login in javascript. In which you have write down the code to redirect the page.
You forgot to prevent the form to submit and that is why you are redirecting to the same page with filled-up values.
If you want to submit your form to specific URL then you should add the action attribute to the form like below.
<form name=loginForm action="URL on which you want to submit form" onsubmit="login()" style="display: inline-block;">
If you want to redirect from the login() function then you should pass the event as an argument from the form and then prevent form submission from the login() function. Please check the below code.
In your form: <form name=loginForm onsubmit="login(event)" style="display: inline-block;">
Change Login function:
function login(e) {
e.preventDefault();
let uname = document.forms["loginForm"]["uname"].value;
let pwd = document.forms["loginForm"]["psw"].value;
window.location.href="main.html";
}
NOTE! Don't forget to pass event in login function
Try this:
window.location.replace('main.html');
In onsubmit function, you can't redirect the page
First, In your form tag, add an action attribute
<form name=loginForm onsubmit="login()" action="main.html" style="display: inline-block;">
Second, Fixed your login function
function login() {
let uname = document.forms["loginForm"]["uname"].value;
let pwd = document.forms["loginForm"]["psw"].value;
return false;
}
Check the redirect URL that contains your data
Try This:
<html>
<head>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
button:hover {
opacity: 0.8;
}
.container {
padding: 16px;
width: 400px;
align-self: center;
}
span.psw {
padding-top: 16px;
}
</style>
<title>Login Page</title>
</head>
<body style="text-align: center;">
<h2 style="text-align: center;">The Mega Cart</h2>
<form name=loginForm onsubmit="login()" style="display: inline-block;">
<div class="container" style="text-align: center;">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="button" onclick="login()">Login</button>
</div>
<span class="psw">New user Sign up here. Sign Up</span>
</div>
</form>
</body>
<script>
function login() {
let uname = document.forms["loginForm"]["uname"].value;
let pwd = document.forms["loginForm"]["psw"].value;
window.location.href = "https://minisoft.com.bd/";
return false;
}
</script>
</html>

Basic Form Validation with the DOM

JS newbie here. I have been trying to learn basic front end on my own and tried to create this form validation but my error messages are not working properly. If a field is empty I want each field to return their own error message but somethings are overwriting others.
Attaching the codes and the screenshot.
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Form Validator</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<form id="all-form" action="">
<h3>Register with us</h3>
<div class="form-control">
<label for="Username">Username</label>
<input id="user" type="username" placeholder="Enter Username" />
<small>error message</small>
</div>
<div class="form-control">
<label for="email">Email</label>
<input id="mail" type="email" placeholder="Enter Email" />
<small>error message</small>
</div>
<div class="form-control">
<label for="password">Password</label>
<input id="pass" type="password" placeholder="Enter Password" />
<small>error message</small>
</div>
<div class="form-control">
<label for="password">Confirm Password</label>
<input id="pass-again" type="password" placeholder="Enter Password Again" />
<small>error message</small>
</div>
<button type="submit" class="submit-btn">Submit</button>
</div>
</form>
<script src="app.js"></script>
</body>
</html>
:root{
--success-color:#2ecc71;
--error-color:#e74c3c;
}
*{
margin:0px;
padding: 0px;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
.container{
position: relative;
top:10em;
margin: auto;
background-color: #fff;
width: 400px;
border-radius: 5px;
box-shadow:0 2px 10px rgba(0,0,0, 0.3);
}
form{
padding:20px 20px;
}
h3 {
text-align: center;
}
label, input{
display: block;
margin:5px;
width: 90%;
}
label{
padding-top: 15px;
padding-right: 15px;
text-align: left;
margin-bottom: 5px;
}
input{
padding:3px;
border-radius: 5%;
font-size: 14px;
}
.submit-btn{
display: block;
padding:10px;
background-color: royalblue;
color: white;
cursor: pointer;
border-radius: 4px;
font-size: 16px;
margin-top:20px;
width: 100%;
}
input:focus{
outline:0;
border-color: #777;
}
.form-control.success input{
border-color: var(--success-color);
}
.form-control.error input{
border-color: var(--error-color);
}
.form-control small{
color:var(--error-color);
position: relative;
bottom:1px;
left:7px;
visibility: hidden;
}
.form-control.error small{
visibility: visible;
}
// Selectors
const username = document.querySelector("#user");
const mail = document.querySelector("#mail");
const pass = document.querySelector("#pass");
const passAgain= document.querySelector("#pass-again");
const sbtBtn = document.querySelector(".submit-btn");
const form = document.querySelector("#all-form");
// Event Listeners
function showError(input,message){
const formControl = input.parentElement;
formControl.className = "form-control error";
const small = document.querySelector("small");
small.innerText = message;
}
function showSuccess(input){
const formControl = input.parentElement;
formControl.className = "form-control success";
}
form.addEventListener("submit",checkAll);
function checkAll(e){
e.preventDefault();
if(username.value === ""){
showError(username, "Username is required");
} else {
showSuccess(username);
}
if(mail.value === ""){
showError(mail, "E-mail is required");
} else {
showSuccess(mail);
}
if(pass.value === ""){
showError(pass, "Password is required");
} else {
showSuccess(pass);
}
if(passAgain.value === ""){
showError(passAgain, "Enter password again please");
} else {
showSuccess(passAgain);
}
}

Login validation function

I have been trying to get this to work for a while now. I cannot connect the login function to the form.
I have tried onsubmit on both the form tag and the button input tag, i have tried onclick but it does not get the code from js function.
index1.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Google maps</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!--<link rel="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="util.js"></script>
<script src="JavaScript.js"></script>
<script type="text/javascript"></script>
<style>
#container {
width: 1200px;
}
#map {
width: 80%;
min-height: 600px;
/*float: right;*/
margin-top: 15px;
margin-left: auto;
margin-right: auto;
}
#img {
width: 150px;
height: 150px;
float: left;
margin-top: auto;
}
/*sökruta*/
#searchBox {
background-color: #ffffff;
padding: 5px;
font-family: 'Roboto','sans-serif';
margin-bottom: 10px;
float: top;
}
/*
html, body {
height: 100%;
margin: 0;
padding: 0;
}
*/
.search-form .form-group {
float: right !important;
transition: all 0.35s, border-radius 0s;
width: 32px;
height: 32px;
background-color: #fff;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
border-radius: 25px;
border: 1px solid #ccc;
}
.search-form .form-group input.form-control {
padding-right: 20px;
border: 0 none;
background: transparent;
box-shadow: none;
display:block;
}
.search-form .form-group input.form-control::-webkit-input-placeholder {
display: none;
}
.search-form .form-group input.form-control:-moz-placeholder {
/* Firefox 18- */
display: none;
}
.search-form .form-group input.form-control::-moz-placeholder {
/* Firefox 19+ */
display: none;
}
.search-form .form-group input.form-control:-ms-input-placeholder {
display: none;
}
.search-form .form-group:hover,
.search-form .form-group.hover {
width: 100%;
border-radius: 4px 25px 25px 4px;
}
.search-form .form-group span.form-control-feedback {
position: absolute;
top: -1px;
right: -2px;
z-index: 2;
display: block;
width: 34px;
height: 34px;
line-height: 34px;
text-align: center;
color: #3596e0;
left: initial;
font-size: 14px;
}
.form-group {
max-width: 300px;
margin-right: auto;
margin-left: auto;
}
</style>
</head>
<body id="container">
<img id="img" src="http://www2.math.su.se/icsim/images/sterik.jpg" alt="Stockholm"/>
<div class="row">
<br>
<div class="col-md-4 col-md-offset-3">
<form action="" class="search-form">
<div class="form-group has-feedback">
<label id="Search" class="sr-only">Search</label>
<input type="text" class="form-control" name="search" id="searchField" placeholder="Sök">
<span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>
</form>
</div>
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="submit" id="login" value="Logga in" onclick="login()">
</form>
</div>
<div id="map">
</div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDNPkC40KP9lMKHUsJW7q403qnwRqYkTno&callback=initMap">
</script>
</div>
</body>
JavaScript.js
function login() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if(username === "admin"
&& password === "123" )
{
alert( "validation succeeded" );
location.href="adminView.php";
}
else
{
alert( "validation failed" );
location.href="index1.html";
}
}
I have created working JSFiddle - Please Check : https://jsfiddle.net/5w6fg52m/1/
Below Code working fine :
<script>
//just change function name as it's conflict with button id
function login1() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if(username === "admin"
&& password === "123" )
{
alert( "validation succeeded" );
location.href="adminView.php";
}
else
{
alert( "validation failed" );
location.href="index1.html";
}
return false;
}
</script>
//HTML
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="button" id="login" value="Logga in" onclick="return login1();">
</form>
</div>
-> I have created other version of JSFiddle, so you come to know conflict issue easily: https://jsfiddle.net/5w6fg52m/2/
Here i have keep function name same(login) and change ID of submit button.
You can set the submit event directly to your like
document.getElementById("loginForm").onsubmit = function() { ... };
Bellow a sample snippet :
window.onload = function(){
document.getElementById("loginForm").onsubmit = function() {
//spara username och password i två varibler med samma namn från formet.
var username = document.getElementById("user").value;
var password = document.getElementById("password").value;
if (username === "admin" &&
password === "123") {
alert("validation succeeded");
//location.href = "adminView.php";
} else {
alert("validation failed");
//location.href = "index1.html";
}
// to prevent submit
return false;
}
}
<div class="form-group">
<form id="loginForm" name="loginForm" method="POST">
<label for="user">Användarnamn: </label>
<br>
<input class="form-control" type="text" id="user" name="user" required>
<br>
<label for="password">Lösenord: </label>
<br>
<input class="form-control" type="password" id="password" name="passwords" required>
<br>
<br>
<input class="form-control" type="submit" id="login" value="Logga in">
</form>
</div>
This happens when you declare variable or function with the same name as declare before. just rename login function or rename id="login".

How to set up user accounts with Meteor?

I'm trying to set up user accounts with my Meteor app. Right now I have the login and register forms made, but they don't work. Does anyone know how to do this? Here is the code I have: http://jsfiddle.net/5AMWE5T/X8aJf/1/
html:
<body>
<div id="topbar">
<form id="login-form" action="/">
<div>
<input type="email" id="login-email" />
<input type="password" id="login-password" />
<input type="submit" class="btn btn-info" id="login-button" value="Sign in" />
</div>
</form>
</div>
<div id="register-box">
<form id="register-form" action="action">
<div>
<input type="username" id="account-username" placeholder=" Username" />
<input type="email" id="account-email" placeholder="Email" />
<input type="password" id="account-password" placeholder="Password" />
<input type="submit" class="btn btn-success" id="create-account" value="Sign up" />
</div>
</form>
</div>
css:
#topbar {
height: 40px;
width: 100%;
opacity: 1;
background-color: #47a7d3;
box-shadow: 0.1em 0.1em 0.1em;
position: absolute;
top: 0;
left: 0;
padding: 0;
}
#register-form {
text-align: center;
margin-top: 15px;
}
#account-username {
margin-bottom: 0.75em;
border-radius: 0.3em;
border-width: 0.1em;
border-color: #ffffff;
width: 15.4em;
margin-left: 0.1em;
height: 1.8em;
box-shadow: 0 0 0.1em #676767;
}
#login-form {
position: absolute;
width: 100%;
top: 0.3em;
letter-spacing: 0.1em;
right: 0.33em;
text-align: right;
}
#login-email {
width: 180px;
}
#login-password {
width: 100px;
}
#login-button {
position: relative;
top: -5px;
font-family:'Montserrat Alternates';
font-size: 12px;
color: #ffffff;
letter-spacing: 0.05em;
}
javascript:
Template.login.events({
'submit #login-form': function (e, t) {
e.preventDefault();
// retrieve the input field values
var email = t.find('#login-email').value,
password = t.find('#login-password').value;
// Trim and validate your fields here....
var trimInput = function (val) {
return val.replace(/^\s*|\s*$/g, "");
}
var email = trimInput(email);
// If validation passes, supply the appropriate fields to the
// Meteor.loginWithPassword() function.
Meteor.loginWithPassword(email, password, function (err) {
if (err)
// The user might not have been found, or their password
// could be incorrect. Inform the user that their
// login attempt has failed.
console.log("Your email or password are incorrect")
else
// The user has been logged in.
console.log("You have been logged in!")
});
return false;
}
});
Your code wouldn't work with a fiddle btw.
A couple of things:
Make sure you have accounts-password installed you can do this with meteor add accounts-password
You haven't given the code for registrations but assuming you use an email for registration, you should log in this way with the {email: email}.
Meteor.loginWithPassword({email: email, password, function (err) {
It would also be a bit more helpful if you gave a bit more info on how you feel it doesn't work. Does submitting the page refresh the page? Do you have any javascript errors in your console? Do you get an error message back?

Categories