"Submit" Form and Direct to Javascript Generated URL - javascript

I have a login form that, when completed, sends users to a page with a JavaScript generated URL (allowing me to pass a JavaScript variable to my PHP script using $_GET). However, in order to do that, the Login button is currently 'type="button"'. While everything works, it means that users cannot login by hitting Enter; they must actually click the Login button. Is there a way I can "Submit" the form, while still having it point to the JavaScript generated URL?
This seems like a pretty basic concept, which tells me I might be approaching it the wrong way to begin with. Any guidance is appreciated.
HTML:
<form name="login">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
</form>
JavaScript:
function check(form) {
var userCredentials = [["jsmith", "smithpassword", "John Smith"], ["jdoe", "doepassword", "Jane Doe"]];
var credCheck = 0;
for (var i = 0; i < userCredentials.length; i++) {
if (userCredentials[i][0] == form.user_id.value) {
credCheck += 1;
var displayName = userCredentials[i][2];
if (userCredentials[i][1] == form.pswrd.value) {
window.open("home.php?display_name=" + displayName, "_self");
} else {
alert('The username and password do not match.');
return false;
}
}
}
if (credCheck == 0) {
alert('The username entered is not valid.');
return false;
} else {
return true;
}
}

Instead of opening php page via javascript, you need to change the form action dynamically to point to your generated url.
HTML:
<form name="login">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="submit" onclick="check(this.form)" value="Login"/>
</form>
JavaScript: (line 9 & 10 changed)
function check(form) {
var userCredentials = [["jsmith", "smithpassword", "John Smith"], ["jdoe", "doepassword", "Jane Doe"]];
var credCheck = 0;
for (var i = 0; i < userCredentials.length; i++) {
if (userCredentials[i][0] == form.user_id.value) {
credCheck += 1;
var displayName = userCredentials[i][2];
if (userCredentials[i][1] == form.pswrd.value) {
form.action = "home.php?display_name=" + displayName;
return true;
} else {
alert('The username and password do not match.');
return false;
}
}
}
if (credCheck == 0) {
alert('The username entered is not valid.');
return false;
} else {
return true;
}
}

You could try:
<form name="login" onsubmit="check(this)">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="submit" value="Login"/>
</form>

Related

Submitting an HTML form to a PHP file with JS validation

I'm sending data via an HTML form to a PHP file for it to be inserted into a DB with SQL script,
The same form is validated with JavaScript functions.
Each of the two works as expected separately,
but when used together - <form method="POST" action="myPHPFile.php" onsubmit="validationFunc(event)"> -
only the validation function works, and the page doesn't get redirected to the PHP file.
When removing the JS (leaving only <form method="POST" action="myPHPFile.php">) - the data from the form is submitted properly and the page is redirected to the PHP file as expected.
I need to have some JS function to stop if the input is invalid,
and another to continue and send the input data to the PHP file if it's valid.
Example code:
function isInputChars(evt) {
let ch = String.fromCharCode(evt.which);
if (!(/[a-z,A-Z,-]/.test(ch))) {
alert("Please only enter only characters")
evt.preventDefault();
}
}
function validateForm(event) {
event.preventDefault();
var validateFormInputs = [];
var inputLength;
StringInput = document.getElementById("city");
StringInput = StringInput.value;
inputLength = StringInput.length;
if (inputLength < 2) {
alert("City: Please enter at least 2 Characters")
validateFormInputs.push(false);
} else {
validateFormInputs.push(true);
}
StringInput = document.getElementById("street");
StringInput = StringInput.value;
inputLength = StringInput.length;
if (inputLength < 2) {
alert("Street: Please enter at least 2 Characters")
validateFormInputs.push(false);
} else {
validateFormInputs.push(true);
}
var x;
for (var i = 0; i < 2; i++) {
if (validateFormInputs[i] === false) {
x = false;
break;
} else {
x = true;
}
}
if (x == true) {
console.log("Data is sent to DB")
someFunctionToContinueSendingTheData();
} else {
console.log("Data is INVALID")
someFunctionToStop();
}
}
<form name="myForm" method="POST" action="sendItem.php" onsubmit="validateForm(event)">
<input id="city" name="city" type="text" class="form-control" onkeypress="isInputChars(event)" required>
<input id="street" name="street" type="text" class="form-control" onkeypress="isInputChars(event)" required>
<input type="submit" class="btn btn-primary btn-lg" value="Publish">
</form>
I'd be happy for some help with:
How to redirect the input data to the PHP file (without removing the JS validation)
How to implement the JS functions to send the data to the PHP/cancel.
Thank you!
Instead of the button being a submit button just have it be a regular button that calls your javascript function. Then, do all of your validation in the function... at the end, you can have a conditional statement which checks if all conditions are met. If they are, then submit the form. (Assign an id to your form)
Check out this pseudo-code
let me know if this works or you need further instruction
function validateForm(){
... conditional logic ...
if(all conditions met){
document.getElementById('form-id').submit();
}
}
It simple you need to use AJAX to Send a Request To your PHP Server
i will show you a simple example
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object.
you can use POST or GET
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
A cached file is not an option (update a file or database on the server).
Sending a large amount of data to the server (POST has no size limitations).
Sending user input (which can contain unknown characters), POST is more robust and secure than GET.
<script type="text/javascript">
function myFunction() {
var name = document.getElementById("name").value; // get the name
var email = document.getElementById("email").value; // get the mail
var xhttp = new XMLHttpRequest();
var url = 'test.php'; // your php file
xhttp.open('POST', url, true); // method =POST
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// send data
var params="name="+name+"&email="+email;
xhttp.onreadystatechange = function() {
//Call a function when the state changes.
if(xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText);
}
}
xhttp.send(params);
}
</script>
<form name="myform" method="POST">
<input type="text" name="name" id="name">
<input type="mail" name="email" id="email">
<input class="btn btn-success" type="button" name="conf" value="OK" onclick="myFunction()">
<input class="btn btn-danger" type="reset" name="cancel" value="cancel">
</form>
You need some changes in your code:
First: you can set validation function on the submit input.
<input type="submit" class="btn btn-primary btn-lg" value="Publish" onclick = "return validateForm();">
Second: you must return true or false at validation function.
if (x == true) {
console.log("Data is sent to DB");
return true; //input data is valid!
someFunctionToContinueSendingTheDate();
} else {
console.log("Data is INVALID")
someFunctionToStop();
return false; //input data is invalid!
}
Finally: here you are:
HTML:
<form name="myForm" method="POST" action="sendItem.php">
<input id="city" name="city" type="text" class="form-control" onkeypress="isInputChars(event)" required>
<input id="street" name="street" type="text" class="form-control" onkeypress="isInputChars(event)" required>
<input type="submit" class="btn btn-primary btn-lg" value="Publish" onclick="return validateForm();"></form>
JS:
<script>
function isInputChars(evt) {
let ch = String.fromCharCode(evt.which);
if (!(/[a-z,A-Z,-]/.test(ch))) {
alert("Please only enter only characters")
evt.preventDefault();
}
}
function validateForm() {
var validateFormInputs = [];
var inputLength;
StringInput = document.getElementById("city");
StringInput = StringInput.value;
inputLength = StringInput.length;
if (inputLength < 2) {
alert("City: Please enter at least 2 Characters")
validateFormInputs.push(false);
} else {
validateFormInputs.push(true);
}
StringInput = document.getElementById("street");
StringInput = StringInput.value;
inputLength = StringInput.length;
if (inputLength < 2) {
alert("Street: Please enter at least 2 Characters")
validateFormInputs.push(false);
} else {
validateFormInputs.push(true);
}
var x;
for (var i = 0; i < 2; i++) {
if (validateFormInputs[i] === false) {
x = false;
break;
} else {
x = true;
}
}
if (x == true) {
console.log("Data is sent to DB");
return true;
someFunctionToContinueSendingTheDate();
} else {
console.log("Data is INVALID")
someFunctionToStop();
return false;
}
}</script>

Using HTML WebStorage to have multiple username and passwords

I am using WebStorage to make a simple login system with username/password. (I don't know if this is the best way.)
It is working, but the problem is, it only works with one username and password. How do I make it so that it can store multiple usernames/passwords? Or perhaps I should be using a different system to do this?
Code:
<html>
<head>
</head>
<body>
<input type="text" placeholder="input username here" id="textbox">
<input type="text" placeholder="input password here" id="textbox2">
<input type="button" value="sign up" onclick="signup()">
<br>
<input type="text" placeholder="input username here" id="textbox3">
<input type="text" placeholder="input password here" id="textbox4">
<input type="button" value="login" onclick="login()">
<p id="result"></p>
<br>
<br>
<div id="settings">
<h1>Settings</h1>
<br>
<input type="text" placeholder="background color" id="bgc">
<br>
<input type="button" onclick="changeSettings()" value="Change settings">
</div>
<script>
function changeSettings() {
if(loggedIn == true) {
if(typeof(Storage)!= "undefined") {
var backg = document.getElementById("bgc").value;
if(backg!="") {
localStorage.setItem("backgroundColor", backg);
document.body.style.background = localStorage.getItem("backgroundColor");
} else {
alert("Enter a color.")
}
} else {
alert("No support.")
}
} else {
alert("You must be logged in to do that.")
}
}
function loadSettings() {
if(typeof(Storage)!="undefined") {
document.body.style.background = localStorage.getItem("backgroundColor");
} else {
alert("No support.")
}
}
function signup() {
if(typeof(Storage)!= "undefined") {
var username = document.getElementById("textbox").value;
var password = document.getElementById("textbox2").value;
if(username!="" && password!="") {
localStorage.setItem("username", username);
localStorage.setItem("password", password);
} else {
alert("Please enter a valid username and password.")
}
} else {
alert("No support.")
}
}
function login() {
if(typeof(Storage)!= "undefined") {
var username = localStorage.getItem("username");
var password = localStorage.getItem("password");
var usernameInput = document.getElementById("textbox3").value;
var passwordInput = document.getElementById("textbox4").value;
if(usernameInput!="" && passwordInput!="") {
if(usernameInput == username && passwordInput == password) {
document.getElementById("result").innerHTML = "Logged in!";
loggedIn = true;
loadSettings();
} else {
document.getElementById("result").innerHTML = "Wrong password/username!";
}
} else {
alert("Please enter a valid username and password.")
}
} else {
alert("No support.")
}
}
</script>
</body>
</html>
ps: sorry if it's messy :p
You should probably be using SQL if you want to store user inputs such as Usernames and Passwords.
Hashing & Password Storage
Good video to watch if your trying to learn Databases!
:)
Not a good way to store the plain username/password in localStorage. anyone can change those value. Since you check the login using
localStorage.setItem("username", username);
localStorage.setItem("password", password);
var username = localStorage.getItem("username");
var password = localStorage.getItem("password");
usernameInput == username && passwordInput == password
This login condition can make true using different ways.
Found this article from the Google, Hope you'll get some idea to do in
secure way :)

Form validation error message is overriding in javascript (only )

Hope, you all doing well.
I am trying to validate firstname input field of a form with Javascript. For some reason, error messages doesn't display in order. Some of them override others, only just one error message is displaying, the rest is not.
I'm wondering why? Can anyone shed me some light please?
Here is my code:
// Predefined validator function to check if input is empty or not
var validator = {};
validator.isEmpty = function(input) {
// Stop execution if input isn't string
if (typeof input !== 'string') return false;
if (input.length !== 0) {
for (var i = 0; i < input.length; i++) {
if (input[i] !== " ") {
return false;
}
return true;
}
}
return true;
};
validator.isEmpty(null); // returns false
// Main part to get inputs and apply validation
window.onload = function() {
var signUp = document.getElementById("signUp");
var fName = document.getElementById("fName");
var suButton = document.getElementById("subMit");
// Submit button on the function
suButton.addEventListener('click', function(event) {
isNameValid(fName);
});
signUp.addEventListener('submit', function(event) {
event.preventDefault();
});
function isNameValid(char) {
var val = char.value;
if (validator.isEmpty(val)) {
if (val.length < 2) {
// Display a message if input length is less than 2
char.setCustomValidity("We expect your input should contain at least 2 characters, darling !");
char.style.borderColor = "red";
}
if(!isNaN(val)) {
char.setCustomValidity("Please, enter only characters");
char.style.borderColor = "red";
}
} else {
char.setCustomValidity("");
char.style.borderColor = "green";
}
}
<form id="signUp">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
It took me a while but I hope following works for you. Let me know if you need help understanding anything. I felt your code was a bit complex so I simplified it.
<script>
function submitForm(){
var formValid = false;
var msg = "";
var fNameElement = document.getElementById("fName");
if(fNameElement){
var fNameValue = fNameElement.value;
if(fNameValue.length < 2){
msg = "We expect your input should contain at least 2 characters, darling !";
}
else if(!(/^[a-zA-Z]+$/.test(fNameValue))){
msg = "Please, enter only characters";
}
else{
formValid = true;
}
if(formValid){
fNameElement.style.borderColor="green";
//do something
}
else{
fNameElement.style.borderColor="red";
alert(msg); // or show it in a div
}
}
}
</script>
<form id="signUp" action="javascript:submitForm()">
<input type="text" id="fName" name="firstname" placeholder="First name">
<input type="checkbox" name="result" required autofocus> Agree our conditions
<input type="submit" id='subMit' value="SUBMIT">
</form>
Fiddle: https://jsfiddle.net/fxumcL3d/3/

Can't submit form through javascript to php

I have a form in html which I want to run verification in Javascript first before POST ing to PHP. However the link up to the PHP section does not seem to be working despite the fact that I have assigned names to each input tag and specified an action attribute in the form tag.
Here is the HTML code for the form:
<form id="signupform" action="signupform.php" method="post">
<input type="text" name="Email" placeholder="Email Address" class="signupinput" id="email" />
<br />
<input type="password" name="Password" placeholder="Password" class="signupinput" id="passwordone" />
<br />
<input type="password" placeholder="Repeat Password" class="signupinput" id="passwordtwo" />
<br />
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="submit" />
</form>
The button calls the javascript function which I use to verify the values of my form before sending to php:
function verifypass() {
var form = document.getElementById("signupform");
var email = document.getElementById("email").value;
var password1 = document.getElementById("passwordone").value;
var password2 = document.getElementById("passwordtwo").value;
var emailcode = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (emailcode.test(email)) {
if (password1.length > 6) {
if (password1 == password2) {
form.submit(); //this statement does not execute
} else {
$("#passwordone").notify("Passwords do not match!", {
position: "right"
})
}
} else {
$("#passwordone").notify("Password is too short!", {
position: "right"
})
}
} else {
$("#email").notify("The email address you have entered is invalid.", {
position: "right"
})
}
}
For some reason, some JavaScript implementations mix up HTML element IDs and code. If you use a different ID for your submit button it will work (id="somethingelse" instead of id="submit"):
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="somethingelse" />
(I think id="submit" has the effect that the submit method is overwritten on the form node, using the button node. I never figured out why, perhaps to allow shortcuts like form.buttonid.value etc. I just avoid using possible method names as IDs.)
I'm not sure why that's not working, but you get around having to call form.submit(); if you use a <input type="submit"/> instead of <input type="button"/> and then use the onsubmit event instead of onclick. That way, IIRC, all you have to do is return true or false.
I think it would be better if you do it real time, for send error when the user leave each input. For example, there is an input, where you set the email address. When the onfocusout event occured in Javascript you can add an eventlistener which is call a checker function to the email input.
There is a quick example for handling form inputs. (Code below)
It is not protect you against the serious attacks, because in a perfect system you have to check on the both side.
Description for the Javascript example:
There is two input email, and password and there is a hidden button which is shown if everything is correct.
The email check and the password check functions are checking the input field values and if it isn't 3 mark length then show error for user.
The showIt funciton get a boolean if it is true it show the button to submit.
The last function is iterate through the fields object where we store the input fields status, and if there is a false it return false else its true. This is the boolean what the showIt function get.
Hope it is understandable.
<style>
#send {
display: none;
}
</style>
<form>
<input type="text" id="email"/>
<input type="password" id="password"/>
<button id="send" type="submit">Send</button>
</form>
<div id="error"></div>
<script>
var fields = {
email: false,
password: false
};
var email = document.getElementById("email");
email.addEventListener("focusout", emailCheck, false);
var password = document.getElementById("password");
password.addEventListener("focusout", passwordCheck, false);
function emailCheck(){
if(email.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Email";
fields.email = false;
} else {
fields.email = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log("asdasd"+show);
showIt(show);
}
function passwordCheck(){
if(password.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Password";
fields.password = false;
} else {
fields.password = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log(show);
showIt(show);
}
function showIt(show) {
if (show) {
document.getElementById("send").style.display = "block";
} else {
document.getElementById("send").style.display = "none";
}
}
function checkFields(){
isFalse = Object.keys(fields).map(function(objectKey, index) {
if (fields[objectKey] === false) {
return false;
}
});
console.log(isFalse);
if (isFalse.indexOf(false) >= 0) {
return false;
}
return true;
}
</script>

html form with javascript window.location not working

I added this code to my website:
<script>
function checkPassword(name, pwd) {
if (name == "jamie") {
if (pwd == "198237645") {
window.location = "member.html"
} else {
document.write("Wrong Password!")
}
} else {
document.write("Wrong Name!")
}
}
</script>
<form action="">
Login Name : <input type="text" name="loginname"><br>
Login Pwd : <input type="password" name="loginpwd"><br>
<input type="submit" onclick="checkPassword(this.form.loginname.value,this.form.loginpwd.value)" value="Login">
</form>
However, after i inserted the correct password & name, i only see the link became:
http://tool-box.weebly.com/test.html?loginname=jamie&loginpwd=198237645
What should i do? if i change window.location="member.html" to document.write("Password Correct!"), it worked correctly.
Please help.
You need to cancel the click action so the form does not submit
onclick="checkPassword(this.form.loginname.value,this.form.loginpwd.value); return false;"
I hope you realize this is NOT secure.
Couple of error in code
a) onclick of submit button doesn't return anything hence the form is submitted each time
b) use window.location.href
<script>
function checkPassword(name, pwd) {
if (name == "jamie") {
if (pwd == "198237645") {
window.location.href = "memeber.html"
} else {
document.write("Wrong Password!")
}
} else {
document.write("Wrong Name!")
}
return false;
}
</script>
<form action="" >
Login Name : <input type="text" name="loginname"><br>
Login Pwd : <input type="password" name="loginpwd"><br>
<input type="submit" onclick = "return checkPassword(this.form.loginname.value,this.form.loginpwd.value)" value="Login">
</form>

Categories