Making HTML/Javascript form submission asynchronous - javascript

I currently have a form with a few variables like username, password, and email which sends the data to a node.js server. Before sending the data, I have a few checks such as whether the inputs are valid and whether the email already exists in my file. The checking aspect of my code works, however the javascript function which I use to check returns before opening the file to check for duplicate emails. I feel that if I could somehow make the onsubmit function asynchronous, that would help.
Here is my code and the segment where I check for duplicate emails is near the end:
<html>
<body>
<form id='form' action="/signup.html" method="POST" onsubmit="return submitIt();">
<div style="text-align:center">
<label for="name">Full Name</label><br>
<input type="text" size="100" id="name" name="name" placeholder="Enter Your Full Name: "><br><br>
<label for="email">Email</label><br>
<input type="text" size="100" id="email" name="email" placeholder="Enter Your Email: "><br><br>
<label for="password">Password</label><br>
<input type="text" size="100" id="password" name="password" placeholder="Enter Your Password: "><br><br>
<button type="submit" id="submit">Submit</button>
</div>
</form>
</body>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
var ret = true;
async function submitIt() {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let password = document.getElementById("password").value;
if (name == "" || name.length < 4) {
document.getElementById("name").value = "";
document.getElementById("name").placeholder = "Please enter a real name";
ret = false;
}
if (email == "" || email.length < 4) {
document.getElementById("email").value = "";
document.getElementById("email").placeholder = "Please enter a real email";
ret = false;
}
if (ret) {
let found = false;
for (let i = 0; i < email.length; i++) {
if (email[i] == '#') {
found = true;
}
}
if (!found) {
document.getElementById("email").value = "";
document.getElementById("email").placeholder = "Please enter a real email";
ret = false;
}
}
if (password.length < 5) {
document.getElementById("password").value = "";
document.getElementById("password").placeholder = "Password must be atleast 5 characters.";
ret = false;
}
await $.ajax({
type:"POST",
url:'/getUsers',
dataType: "text",
success: function(content) {
let contents = content.split('\n');
for (let i = 0; i < contents.length; i += 3) {
if (contents[i] == email) {
document.getElementById("email").value = "";
document.getElementById("email").placeholder = "Email already in use.";
ret = false;
}
}
}
});
return ret;
}
</script>
</head>
</html>
Any help would be greatly appreciated!

Have you tried moving onSumbmit call from form to the button?
const submitButton = document.getElementById(***)
submitButton.addEventListener('click', () => {your code})
Another way could be preventing default behavior of the submit form.
async function submitIt(event) {
event.preventDefault;
event.stopImmediatePropagation;
....your code....
}
I don't have access to a PC right now to check it, but one of the provided solutions should work. Cheers!

Related

JS Form event and validation

I hope somebody can help me find the error in this code, i need to use simple js to create a form that only submits if there are no errors, The user name must be a valid email. The password and retyped password must be 8 characters and include one uppercase, one lowercase and one numeric. The password
and the retyped password must match. I need to make use of a regular
expression to constrain the password.
If the data rules are violated, a appropriate error messages should be displayed
and the form should be stopped from submitting.Can someone help me with why it is not doing what it is supposed to? Im still new to js and any hel would be appreciated.
function handleInvalidities(input) {
let errMsg = " ";
if (!input.validity.paternMismatch) {
errMsg = "Invalid entry. Enter your details in the format shown.";
}
if (!input.validity.paternMismatch) {
errMsg = "Invalid entry. This field cannot be empty. Please enter a value.";
}
return errMsg;
}
function displayInvalidities(errMsg, elem) {
let elemPos = document.getElementById(elem);
let errElem = document.createElement("span");
errElem.setAttribute("class", "error");
let errText = document.createTextNode(errMsg);
errElem.appendChild(errText);
elemPos.parentNode.insertBefore(errElem, elemPos.nextSibling);
}
function cleanUpErrors() {
let errors = document.getElementsByClassName("error");
for (let i = 0; i < errors.length; i++) {
errors[i].style.display = "none";
}
}
window.onload = () => {
let theForm = document.getElementById("loginform");
theForm.addEventListener("submit");
(event) => {
let stopSubmit = false;
cleanedUpErrors();
for (let i = 0; i < theForm.elements.length; i++) {
if (!theForm.elements[i].checkValidity()) {
displayInvalidities(handleInvalidities(theForm.elements[i]), theForm.Elements[i].id);
stopSubmit = true;
}
}
if (stopSubmit) {
event.preventDefault();
}
}, (false);
}
<section>
<h1>Form: validated using Javascript</h1>
<p>Try entering the following:</p>
<ul>
<li>Password longer or shorter than 8 characters and/or without an uppercase, lowercase or a numeric.</li>
<li>Passwords that do not match</li>
</ul>
<h2>Register</h2>
<p>* = Required Field</p>
<div id="formcontainer">
<form id="regsiterdetails" action="fma_t3confirm.html">
<div>
<label for="username">* Userame:</label>
<input type="text" id="username">
</div>
<div>
<label for="password">* Password (Must be 8 characters and include one uppercase, one lowercase and one numeric):</label>
<input type="password" id="password">
<input type="checkbox" id="showpasswords">
<label id="showpasswordslabel" for="showpasswords">Show passwords</label>
</div>
<div>
<label for="retypedpassword">* Retype your password:</label>
<input type="password" id="retypedpassword">
<span id="passwordmatcherror"></span>
</div>
<div>
<button type="submit" id="registerButton">Register</button>
</div>
</form>
</div>
</section>
You need to fix your event handlers and spelling (Elements) and form ID (registerdetails) and spelling of function names like cleanUpErrors
window.addEventListener("load", () => {
document.getElementById("registerdetails").addEventListener("submit", event => {
const theForm = event.target;
let stopSubmit = false;
cleanUpErrors();
for (let i = 0; i < theForm.elements.length; i++) {
if (!theForm.elements[i].checkValidity()) {
displayInvalidities(handleInvalidities(theForm.elements[i]), theForm.elements[i].id);
stopSubmit = true;
}
}
if (stopSubmit) {
event.preventDefault();
}
})
})
You are setting event listener without any function. Change in your code like this:
window.onload = () => {
let theForm = document.getElementById("regsiterdetails");
theForm.addEventListener("submit",(event) => {
let stopSubmit = false;
cleanedUpErrors();
for (let i = 0; i < theForm.elements.length; i++) {
if (!theForm.elements[i].checkValidity()){
displayInvalidities(handleInvalidities(theForm.elements[i]), theForm.Elements[i].id);
stopSubmit = true;
}
}
if (stopSubmit) {
event.preventDefault();
}
}, (false);
)
}
Also check your code as there is no element with id loginform. I think you should use regsiterdetails instead of loginform.
There was no form element with the id that you're trying to get. Try to get with the actual id which is regsiterdetails and fix your addEventListener parameter list.
function handleInvalidities(input) {
let errMsg = " ";
if (!input.validity.paternMismatch) {
errMsg = "Invalid entry. Enter your details in the format shown.";
}
if (!input.validity.paternMismatch) {
errMsg = "Invalid entry. This field cannot be empty. Please enter a value.";
}
return errMsg;
}
function displayInvalidities(errMsg, elem) {
let elemPos = document.getElementById(elem);
let errElem = document.createElement("span");
errElem.setAttribute("class", "error");
let errText = document.createTextNode(errMsg);
errElem.appendChild(errText);
elemPos.parentNode.insertBefore(errElem, elemPos.nextSibling);
}
function cleanUpErrors() {
let errors = document.getElementsByClassName("error");
for (let i = 0; i < errors.length; i++) {
errors[i].style.display = "none";
}
}
window.onload = () => {
let theForm = document.getElementById("regsiterdetails");
theForm.addEventListener("submit", (event) => {
let stopSubmit = false;
cleanedUpErrors();
for (let i = 0; i < theForm.elements.length; i++) {
if (!theForm.elements[i].checkValidity()) {
displayInvalidities(handleInvalidities(theForm.elements[i]), theForm.Elements[i].id);
stopSubmit = true;
}
}
if (stopSubmit) {
event.preventDefault();
}
}, (false));
}
<section>
<h1>Form: validated using Javascript</h1>
<p>Try entering the following:</p>
<ul>
<li>Password longer or shorter than 8 characters and/or without an uppercase, lowercase or a numeric.</li>
<li>Passwords that do not match</li>
</ul>
<h2>Register</h2>
<p>* = Required Field</p>
<div id="formcontainer">
<form id="regsiterdetails" action="fma_t3confirm.html">
<div>
<label for="username">* Userame:</label>
<input type="text" id="username">
</div>
<div>
<label for="password">* Password (Must be 8 characters and include one uppercase, one lowercase and one numeric):</label>
<input type="password" id="password">
<input type="checkbox" id="showpasswords">
<label id="showpasswordslabel" for="showpasswords">Show passwords</label>
</div>
<div>
<label for="retypedpassword">* Retype your password:</label>
<input type="password" id="retypedpassword">
<span id="passwordmatcherror"></span>
</div>
<div>
<button type="submit" id="registerButton">Register</button>
</div>
</form>
</div>
</section>

Javascript form validation highlight invalid character

I'm just working on some really basic form validation with JS. I don't want users to be able to use any special characters on input fields as a layer of defense against XSS exploits.
I've got the basic validation down and it seems to work ok but it just says there is an error and I would like to highlight the invalid character. here is my code.
HTML
<head><meta charset="UTF-8"><script src="script.js"></script></head>
<body>
<form method="post" action="test.php" onsubmit="return validate()">
<p><input type="text" id="userName" placeholder="Username or Email"></p>
<p><input type="password" id="userEmail" placeholder="Password"></p>
<p><input type="submit" id="submit" value="Login"></p>
</form>
<input type="button" value="debug" onclick="debug()">
<p id="errorText"></p>
<p id="debug"></p>
</body>
Javascript
<script>
function validate() {
var userName = document.getElementById('userName').value;
var userEmail = document.getElementById('userEmail').value;
var invalidChars = "!,#,#,$,%,^,&,*,(,),<,>,/,~,`";
var mergeFields = userName.concat(userEmail);
var found = "false";
var invCharsArr = invalidChars.split(",");
var fieldsArr = mergeFields.split("");
var nameErr = "false";
var emailErr = "false";
for (var i = 0; i < fieldsArr.length; i++) {
if (invCharsArr.indexOf(fieldsArr[i]) > -1) {
found = "true";
break;
}
}
if (found == "true") {
document.getElementById('errorText').innerHTML = "You used an invalid character";
return false;
}
else {
if (userName == "" || userName == null) {
document.getElementById('userName').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
nameErr = "true";
return false;
}
else if (userEmail == "" || userEmail == null) {
document.getElementById('userEmail').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
emailErr = "true";
return false;
}
else {
return true;
}
}
}
</script>
On a side note I am still a beginner with javascript, if there is anything here that I can do better please let me know I would like to learn. Thanks
You can show an error message under the input marking some chars by wrapping them in spans. Doing this on a input field is not possible as far as I know.
<div class="error">Invalid chars in: <span class="mark">#</span>test</div>.
As already mentioned you should not rely on javascript validation only. It mainly helps to prevent sending unnecessary false requests to the server.

Javascript not working in html file

I have written code for a basic registration page to run on my webserver but javascript doesn't seem to be working in the html file. I do a form post with a javascript function to find errors but it seems to be completely ignoring the javascript code when I test it. Is there a problem with my javascript code or in the html code? My code is shown below.
<script type="text/javascript" language="Javascript">
function checkPasswordMatch(){
var password = document.getElementById("pass1").value;
var password2 = document.getElementById("pass2").value;
if(password != password2){
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords do not match!";}
else{
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords match.";}
}
// $(document).ready(function(){
// $("#pass2").keyup(checkPasswordMatch);
// })
function Error() {
var user = document.getElementById("user").value;
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var email = document.getElementById("email").value;
if(user=""){
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}
if(pass1=""){
document.form1.password1.focus();
document.getElementById("passworderror1").innerHTML = "Enter password.";
return false;
}
if(pass2=""){
document.form1.password2.focus();
document.getElementById("passworderror2").innerHTML = "Enter password.";
return false;
}
if(email=""){
document.form1.useremail.focus();
document.getElementById("emailerror").innerHTML = "Enter email";
return false;
}
}
</script>
</head>
<body>
<div id="link">
Home
<a align="right" href="signin">Sign-in</a>
</div>
<div id="header">
<center><h1><i>IMGCAPTURE</i></h1></center>
</div>
<div id="create">
<center><h2>Create Your Account</h2></center>
<form name="form1" action="account" onsubmit="return Error()" method="POST">
<div id="username"><center><h3>Enter Username: <input type="text" name="username" id="user" cols="15" rows="1"></input></h3></center></div>
<div id="usernameerror"></div>
<div id="password"><center><h3>Enter Password: <input type="password" name="password1" id="pass1" cols="15" rows="1"></input></h3></center></div>
<div id="passworderror1"></div>
<div id="confirmpassword"><center><h3>Re-Enter Password: <input type="password" name="password2" id="pass2" onChange="checkPasswordMatch()" cols="15" rows="1"></input></h3></center></div>
<div id="passworderror2"></div>
<div class="registrationFormAlert" id="divcheckpasswordmatch"></div>
<center><h3>Enter Email: <input type="email" name="useremail" id="email" cols="15" rows="1">
</input></h3></center>
<div id="emailerror"></div>
<center><input type="submit" value="Create Account" onclick="Error()"></input></center>
</form>
</div>
</body>
</html>
It may be that you are not calling the functions you are creating. So since you are not calling those functions with arguments, nothing inside them is going to happen. Let me know if this fixes it.
Also, stylistically you would want the Javascript code at the end of the HTML file.
Instead of binding your input name="password2" to the function by the onChange-tag, try binding it like this:
$(document).on('change', 'input[name="checkPasswordMatch"]', checkPasswordMatch);
function checkPasswordMatch() {
...
}
And in your HTML, remove the onChange tag:
<div id="confirmpassword">
<center>
<h3>
Re-Enter Password: <input type="password" name="password2" id="pass2" cols="15" rows="1"></input>
</h3>
</center></div>
It seems you've forgotten to include jQuery. If you use pure JS, it works :
<script type="text/javascript">
function checkPasswordMatch() {
var password = document.getElementById("pass1").value;
var password2 = document.getElementById("pass2").value;
if (password != password2) {
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords do not match!";
} else {
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords match.";
}
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("pass2").addEventListener('keyup', checkPasswordMatch);
});
function Error() {
var user = document.getElementById("user").value;
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var email = document.getElementById("email").value;
if (user = "") {
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}
if (pass1 = "") {
document.form1.password1.focus();
document.getElementById("passworderror1").innerHTML = "Enter password.";
return false;
}
if (pass2 = "") {
document.form1.password2.focus();
document.getElementById("passworderror2").innerHTML = "Enter password.";
return false;
}
if (email = "") {
document.form1.useremail.focus();
document.getElementById("emailerror").innerHTML = "Enter email";
return false;
}
}
</script>
You probably want to use == or === in your if statements. You're assigning user, etc. to an empty string in your if conditionals.
if(user == ""){
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}

Form submission - confirmation

I am currently using the dotmailer to generate a new form (simple textbox and submit button) that automatically adds the email address to the dotmailer address book.
When someone submits an email address - they can be taken to a webpage.
<input type="hidden" name="ReturnURL" id="returnValueHidden" value="URL">
I have been trying to work out a way to present an alert box saying "submitted" and not take take the user to a thank you page.
Solution?
document.getElementById('returnValueHidden').value = alert("Email successfully submitted.");
But all this does, it displays an alert box and then redirects to the following url (even when the value is inserted or not).
http://dmtrk.net/undefined?result=success
404 The page you are looking for could not be found
Is there anyway i can adjust this so it submits the email but does not redirect.
Full Code:
<script language="javascript">
<!--
function validate_signup(frm) {
var emailAddress = frm.Email.value;
var errorString = '';
if (emailAddress == '' || emailAddress.indexOf('#') == -1) {
errorString = 'Please enter your email address';
}
var els = frm.getElementsByTagName('input');
for (var i = 0; i < els.length; i++)
{
if (els[i].className == 'text' || els[i].className == 'date' || els[i].className == 'number')
{
if (els[i].value == '')
errorString = 'Please complete all required fields.';
}
else if (els[i].className == 'radio')
{
var toCheck = document.getElementsByName(els[i].name);
var radioChecked = false;
for (var j = 0; j < toCheck.length; j++)
{
if (toCheck[j].name == els[i].name && toCheck[j].checked)
radioChecked = true;
}
if (!radioChecked)
errorString = 'Please complete all required fields.';
}
}
document.getElementById('returnValueHidden').value = alert("Email successfully submitted.");
var isError = false;
if (errorString.length > 0)
isError = true;
if (isError)
alert(errorString);
return !isError;
}
//-->
</script>
HTML:
<form name="signup" id="signup" action="http://dmtrk.net/signup.ashx" method="post" onsubmit="return validate_signup(this)">
<input type="hidden" name="addressbookid" value="">
<input type="hidden" name="userid" value="41929">
<input type="hidden" name="ReturnURL" id="returnValueHidden" value="URL">
<input type="text" name="Email" onfocus="if(this.value=='Email')this.value='';" class="blueTextBox">
<input type="Submit" name="Submit" class="submit">
</form>
To send information without doing a full page reload you need to use AJAX. It's easiest to use an existing javascript library, for example jQuery.
Check out these pages:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/on/

JS validation fails at normal speed but works when stepping through the code

js validation works perfectly when I step through it, but fails at "normal speed." SPECIFICALLY: if a dup email is caught but the other fields are filled in correctly, the form can be submitted (but no error is forthcoming when stepping through the code). Has anyone seen this before? I know I could just code it a different way, but I cannot simply walk away from this simple problem that's even become a bottle kneck without first understanding why this isn't working.
My approach is to validate onblur and onsubmit. I am using the jquery selector only for convenience and then again for an ajax call, but otherwise i'm using js. I am doing a loop through the fields but only operating on text and password fields.
checking for blanks
checking for no numbers in name
checking for email address properly formatted
and then checking for unique email in the email field
annotated code below for js and form below:
//registration validation
$('.validate').blur(function() {
var theForm = document.registerNewUserForm;
//removes error messages from html before the run
clearAllErrors(theForm);
var msg = "";
var mdiv;
theForm.submit.disabled=true;
document.getElementById("submitButton").disabled = true;
for (var i = 0; i < theForm.elements.length; i++) {
//mdiv is set to form element being evaluated at the time
mdiv = document.getElementById(theForm.elements[i].name + "Message");
msg = validateField(theForm.elements[i]);
if(msg != "") {
mdiv.innerHTML = msg;
break;
}
}
if(msg == "") {
theForm.submit.disabled=false;
document.getElementById("submitButton").disabled = false;
}
});
$('#registerNewUserForm').submit(function() {
var theForm = document.registerNewUserForm;
clearAllErrors(theForm);
var msg = "";
var mdiv;
for (var i = 0; i < theForm.elements.length; i++) {
//mdiv is set to form element being evaluated at the time
mdiv = document.getElementById(theForm.elements[i].name + "Message");
msg = validateField(theForm.elements[i]);
if(msg != "") {
break;
}
}
if (msg != ""){
mdiv.innerHTML = msg;
return false;
} else {
theForm.submit();
}
});
function validateField(theField) {
msg = "";
//all fields are required
if (theField.type == "text" || theField.type == "password") {
if (theField.value == "") {
msg = "The " + theField.name + " field is required.";
}
}
//name fields are non-numeric
if (theField.name == "fullName"){
if (hasNumber(theField.value) == true){
msg= "The Name field is non-numeric.";
}
}
//email must be correctly formatted
if (theField.name == "email") {
msg = emailCheck (theField.value);
if (msg == "") {
//email address must also be unique
chkEmail();
msg = document.getElementById('emailMessage').innerHTML;
}
}
return msg;
}
function chkEmail() {
emailAddr = document.getElementById("email").value;
$.ajax({
url: '/chkEmail',
type: 'POST',
data: 'emailAddr=' + encodeURIComponent(emailAddr),
dataType: "xml",
context: document.body,
success: function(data) {
document.getElementById('emailMessage').innerHTML = $(data).find("message").text();
}
});
}
<form name="registerNewUserForm" id="registerNewUserForm" action="/register" method="post">
<br/>
<div>Create an Account and join the fun!</div>
<div><input class="validate" type="text" id="fullName" required placeholder="Full Name" name="fullName" value="" size="30"></div>
<div id="fullNameMessage" class="error"></div>
<div><input class="validate" type="text" id="email" required placeholder="Email Address" name="email" value="" size="30"></div>
<div id="emailMessage" class="error"></div>
<div><input class="validate" type="password" id="passWord" required placeholder="Password" name="passWord" value="" size="30"></div>
<div id="passWordMessage" class="error"></div>
<div style="position:relative;left:173px;"><input id="submitButton" type="submit" value="Signup for PastelPlanet"></div>
<input type="hidden" name="formName" value="registerNewUserForm">
<input type="hidden" name="urlDestination" value="">
</form>
Your "chkEmail" function involves a call to the server, and it's asynchronous. The call to the server will not be complete when the function returns, when you're running at "full speed".

Categories

Resources