Ajax post form - how to resubmit? - javascript

So I have the following form, with an ajax, which to call the server for user authentication. Now the problem is that let's say the user password is wrong. If the user tries to correct it any subsequent call does no longer trigger the on('submit') function thus he is stuck at the page. How can I make it to allow resubmition of the form?
var login_email = document.getElementById("login_email");
var login_password = document.getElementById("login_password");
$(function() {
$('form#login_form').on('submit', function(e) {
console.log("submit");
$.post('/auth_user', $(this).serialize(), function (data) {
console.log(data);
if(data == "No user registered with this email.") {
login_email.setCustomValidity(data);
} else if(data == "Incorrect password.") {
login_password.setCustomValidity(data);
} else {
}
});
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/dashboard" id="login_form" method="post">
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" name="email" id="login_email" required autocomplete="off"/>
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input type="password" name="password" id="login_password" required autocomplete="off"/>
</div>
<p class="forgot">Forgot Password?</p>
<button class="btn btn-primary"/>Log In</button>
</form>

Answer... from discussion above.
Move the credential authentication ajax to the onchange event for both email and password and set a customvalidation message to "invalid username or password" or "" depending on ajax result.

Can you try adding a type submit attribute to your html button tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/dashboard" id="login_form" method="post">
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" name="email" id="login_email" required autocomplete="off"/>
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input type="password" name="password" id="login_password" required autocomplete="off"/>
</div>
<p class="forgot">Forgot Password?</p>
<button class="btn btn-primary" type="submit"/>Log In</button>
</form>
Also you need not put a listener for submit you can use the .submit() function of jquery
$(function() {
$('form#login_form').submit(function(e) {
console.log("submit");
$.post('/auth_user', $(this).serialize(), function (data) {
console.log(data);
if(data == "No user registered with this email.") {
login_email.setCustomValidity(data);
} else if(data == "Incorrect password.") {
login_password.setCustomValidity(data);
} else {
}
});
e.preventDefault();
});
});
The other way is you put a click handler on the button and internally call the .submit() for the form

Related

Signup page button isn't redirecting me to another page

<body>
<h1 style="color:red;">SIGN UP</h1>
<p style="color:blue;">Please fill in this form to create an account.</p>
<label for="Email">Email:</label>
<input type="text" id="Email" name="Email"><br><br>
<label for="password">password:</label>
<input type="text" id="password" name="password"><br><br>
<label for="repeatpassword">repeatpassword:</label>
<input type="text" id="repeatpassword" name="repeatpassword"><br><br>
<button onclick="email" >SIGNUP!</button>
<script>
var email = document.getElementById("Email").value;
function email(){
if(document.getElementById("password").value===document.getElementById("repeatpassword").value && email.include("#")== true){
location.href = "question2.html";
}
}
</script>
</body>
</html>
I want to redirect to another html page when clicking on signup button and email input field contains "#" and password input field value is same as repeatpassword but I don't know what is wrong with my code
Check out with window.location.href in the script function to redirect.
for more reference look out https://www.w3schools.com/js/js_window_location.asp
Button onclick="email()" parenthesis is required because you are calling a function on a button click.
Function can't access a variable declared outside the function. So declare that email var inside the function scope.
It's not email.include() function it's includes(). "s" was missing. Ref -
https://www.w3schools.com/jsref/jsref_includes.asp
function email(){
var email = document.getElementById("Email").value;
if(document.getElementById("password").value===document.getElementById("repeatpassword").value && email.includes("#")== true){
console.log("Working");
}
else{
console.log("Not working");
}
}
<h1 style="color:red;">SIGN UP</h1>
<p style="color:blue;">Please fill in this form to create an account.</p>
<label for="Email">Email:</label>
<input type="text" id="Email" name="Email"><br><br>
<label for="password">password:</label>
<input type="text" id="password" name="password"><br><br>
<label for="repeatpassword">repeatpassword:</label>
<input type="text" id="repeatpassword" name="repeatpassword"><br><br>
<button onclick="email()" >SIGNUP!</button>

Onsubmit does not call function

Trying to verify form input via a jQuery get request, but function does not get called.
Tried using just the jQuery (without function), the $.get works and returns proper values. I need the function approach to return false if (and stop form from submitting) if condition is not met.
<form onSubmit="return checkName();" action="/register" method="post">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
<script>
function checkName() {
$(document).ready(function () {
$("button").click(function () {
$.get("/check?username=" + document.getElementById('1').value, function (data, status) {
alert(data);
return false;
});
});
});
}
</script>
I expect the function to be called, return true if input verified (and go on with form submission) and false (stop form from submitting) if verification fails.
It isn't common practice to put events within the html anymore, as there is addEventListener. You can add it directly from the javascript:
document.querySelector('form').addEventListener('submit', checkName)
This allows for easier code to navigate, and makes it easier to read.
We can then prevent the form form doing it's default action by passing the first parameter to the function, and calling .preventDefault() as you can see from the modified function below. We no longer need to have return false because of it.
document.querySelector('form').addEventListener('submit', checkName)
function checkName(e) {
e.preventDefault()
$.get("/check?username=" + document.getElementById('1').value, function(data, status) {
alert(data);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/register" method="post">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
You're returning false from the async handler function. As such, that's not going to stop the form from being sent.
A better solution would be to always prevent the form from being submit then, based on the result of your AJAX request, submit it manually.
Also note that it's much better practice to assign unobtrusive event handlers. As you're using jQuery this is a trivial task. This also gets you access to the Event object which was raised by the form submission in order to cancel it. Try this:
<form action="/register" method="post" id="yourForm">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
$(document).ready(function() {
$("#yourForm").on('submit', function(e) {
e.preventDefault();
var _form = this;
$.get('/check', { username: $('#1').val() }, function(data, status) {
// interrogate result here and allow the form submission or show an error as required:
if (data.isValid) { // just an example property, change as needed
_form.submit();
} else {
alert("Invalid username");
}
});
});
});
You need to return from function not from inside the callback, and you do one if you assign to onsubmit you don't need click handler. And also click handler will not work if you have action on a form.
You need this:
function checkName() {
$.get("/check?username=" + document.getElementById('1').value, function(data, status){
alert(data);
});
return false;
}
this is base code, if you want to submit the form if data is false, no user in db then you need something like this (there is probably better way of doing this:
var valid = false;
function checkName() {
if (valid) { // if valid is true it mean that we submited second time
return;
}
$.get("/check?username=" + document.getElementById('1').value, function(data, status){
if (data) { // we check value (it need to be json/boolean, if it's
// string it will be true, even string "false")
valid = true;
$('form').submit(); // resubmit the form
}
});
return valid;
}
You can mark all your fields as required if they cannot be left blank.
For your function you may use the below format which works for me.
function checkName() {
var name = $("#1").val();
if ('check condition for name which should return true') {} else {
return false;
}
return true;
}
Just write the name of the function followed by (). no need to write return on onsubmit function call
function checkName()
{
$(document).ready(function(){
$("button").click(function(){
$.get("/check?username=" + document.getElementById('1').value, function(data, status){
alert(data);
return false;
});
});
});
}
<form onSubmit="checkName();" action="/register" method="post">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
I think if you replace button type from submit to button and then on button click event, inside get request, if your condition gets true, submit the form explicitly, would help you too achieve what you require.
You should remove the document.ready and the button event click.
EDITED
Adding an event parameter to checkName :
<form onSubmit="return checkName(event);" action="/register" method="post" id="myForm">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
<script>
function checkName(e){
e.preventDefault();
e.returnValue = false;
$.get("/check?username=" + document.getElementById('1').value,
function(data, status){
if(data) // here you check if the data is ok
document.getElementById('myForm').submit();
else
return false;
});}
</script>

Password verification for webpage in html and javascript

I have a registration webpage where a user inputs information like name and password. There are two inputs for password to verify they are the same password but when I submit the form, it says the passwords don't match, even when they do.
<form id="registration-info" method="POST" action="/registration" >
...
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
<div class="invalid-feedback">
Please enter a password.
</div>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password" required>
<script>
form = document.getElementById("registration-info");
form.onclick = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if(password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
} else {
repeat_password.setCustomValidity('');
}
}
</script>
</div>
There are two problems with your code.
You've put your validation code in an onclick handler on the <form> element. This means the script will never run at all, because the user doesn't click on the <form>, they click on the submit <button>. Instead use an onsubmit handler on the form.
You aren't doing anything to prevent the form from submitting if the password values don't match. One way to do this is to return false from the onsubmit handler.
Here is a corrrected version:
form = document.getElementById("registration-info");
form.onsubmit = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if (password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
console.log("Passwords don't match");
return false; // prevent the form from submitting
} else {
repeat_password.setCustomValidity('');
}
}
// reset the customValidity when the field is modified, so corrected
// values won't trip up on past errors:
document.getElementById("repeat_password").onchange = function(e) {
e.target.setCustomValidity('')
}
.invalid-feedback {display:none}
<form id="registration-info" method="POST" action="/registration">
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
<div class="invalid-feedback">
Please enter a password.
</div>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password" required>
</div>
<input type="submit" value="Submit" id="registration-info-submit">
</form>
Another way to do this -- and to be honest if I'd been familiar with setCustomValidity before this question, this probably would have been my answer in the first place -- might be to set the customValidity message values when the field values change, instead of on form submit. (If a customValidity value is set, it will prevent the form submit from running at all.)
document.getElementById("registration-info").onchange = function() {
var password = document.getElementById("password");
var repeat_password = document.getElementById("repeat_password");
if (password.value != repeat_password.value) {
repeat_password.setCustomValidity("Passwords Don't Match");
} else {
repeat_password.setCustomValidity('');
}
}
<form id="registration-info" method="POST" action="/registration">
<div class="mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" required>
</div>
<div class="mb-3">
<label for="repeat_password">Repeat Password</label>
<input type="password" class="form-control" name="repeat_password" id="repeat_password" required>
</div>
<input type="submit" value="Submit" id="registration-info-submit">
</form>
(But note that this will leave your forms unvalidated in IE9 and below, which do not support setCustomValidity; the first snippet will validate the form in all browsers.)
You did not take the values of the selected ids here. Inatead of taking values after in IF case try the following code. I hope that is the only reason.
var password = document.getElementById("password").value;
var repeat_password = document.getElementById("repeat_password").value;

How to Validate an Email Submission Form When There Are Multiple on the Same Page Using the Same Class?

I have three email forms on one page, all using the same class. When someone enters an email address and submits one of those forms, I want to validate the email address entered into that specific form. The problem that I'm having if is someone enters an email address for one of the later forms, it validates against the data in the first form. How can I make it so my validation function validates for the field into which the email address was entered without having to give each form a unique ID and have the validation code multiple times?
The validation code is below and code for one of the forms. Thanks!
<script>
function validateMyForm() {
var sEmail = $('.one-field-pardot-form-handler').val();
if ($.trim(sEmail).length == 0) {
event.preventDefault();
alert('Please enter valid email address.');
return false;
}
if (validateEmail(sEmail)) {
}
else {
event.preventDefault();
alert('Invalid Email Address. Please try again.'); }
};
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
return true;
}
else {
return false;
}
}
</script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" onSubmit="return validateMyForm();" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
Rather than calling the method from the html onsubmit attribute, wire the whole thing up in jquery.
$('form.myform').submit(function(e){
var $theForm = $(this);
var $theEmailInput = $theForm.find('.one-field-pardot-form-handler');
validateEmail($theEmailInput.val());
});
If you have 3 forms, just target the email field (via the class) within the context of the form.
And, don't use inline HTML event attributes (onsubmit, etc.), there are many reasons why and you can read about those here.
Instead, do all your event binding with JavaScript/JQuery and then you won't need to worry about return false to cancel the event if you are already using .preventDefault(). Additionally, it's best to capture the event reference as an argument to the event callback function, instead of the global event object.
There were other items that should be adjusted as well, so see additional comments inline:
// Get all the form elements and set up their event handlers in JavaScript, not HTML
$("form").on("submit", validateMyForm);
function validateMyForm(evt) {
// First, get the form that is being filled out
var frm = evt.target;
evt.preventDefault();
// Now, just supply the form reference as context for the email search
// Notice the extra argument after the selector "frm"? That tells JQuery
// where within the DOM tree to search for the element.
var sEmail = $('.one-field-pardot-form-handler', frm).val();
// Just to show that we've got the right field:
$('.one-field-pardot-form-handler', frm).css("background-color", "yellow");
// ***************************************************************************
// No need to convert a string to a JQuery object and call .trim() on it
// when native JavaScript has a .trim() string method:
if (sEmail.trim().length == 0) {
evt.preventDefault();
alert('Please enter valid email address.');
}
// Don't have empty branches, reverse the logic to avoid that
if (!validateEmail(sEmail)) {
evt.preventDefault();
alert('Invalid Email Address. Please try again.');
}
}
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return filter.test(sEmail);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
So a combination of #paul and #ScottMarcus' answers above ultimately got me to where I needed to go. Below is what I ended up with and it works as intended. As others have pointed out, I'm definitely a n00b and just learning javascript so certainly may not be perfect:
<script>
$('form.pardot-email-form-handler').submit(function(event) {
var theForm = $(this);
var theEmailInput = theForm.find('.one-field-pardot-form-handler');
var theEmailValue = theEmailInput.val();
function validateEmail(theEmailValue) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(theEmailValue)) {
return true;
} else {
return false;
}
}
if (!validateEmail(theEmailValue)) {
event.preventDefault();
alert('Invalid Email Address. Please try again.');
} else {
return true;
}
});
</script>
<div class="nav-email-form">
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" class="pardot-email-form-handler" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
</div>

JQuery Form Validation not working properly need fixes?

i'm working with the forms and i want when i hit the submit buttom only that field gets red which are empty . don't knw how to fix it . if anyone can help me i'm new javascript and jquery thanks
My HTML
<form id="form">
<div class="form-group">
<label>Username</label>
<p><span id="usernameError"></span></p>
<input type="text" class="form-control" id="username" placeholder="Username">
</div>
<div class="form-group">
<label>Email</label>
<p><span id="emailError"></span></p>
<input type="email" class="form-control" id="email" placeholder="email">
</div>
<div class="form-group">
<label>Password</label>
<p><span id="passwordError"></span></p>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<div class="form-group">
<label>Confirm Password</label>
<p><span id="confPasswordError"></span></p>
<input type="password" class="form-control" id="confPassword" placeholder="Confirm Password">
</div>
<p><span id="warning"></span></p>
<button type="submit" id="submit" class="btn btn-default">Submit</button>
</form>
MY JAVASRIPT
now here is the situation . i put all the variables in one if statement and that's why they all are turning into red
$("#form").submit(function(){
if(password.val() != confPassword.val() )
{
alert("password dont match");
}
if($(this).val() == ""){
username.addClass("border");
email.addClass("border");
password.addClass("border");
confPassword.addClass("border");
// warning message
message.text("PLEASE FILL OUT ALL THE FIELDS").addClass("boldred");
// errors rendering
usernameError.text("username must be defined").addClass("red");
emailError.text("email must be valid and defined").addClass("red");
passwordError.text("password must be defined").addClass("red");
confPasswordError.text("confirm password must be matched and defined").addClass("red");
// disabling submit button
submit.attr("disabled" , "disabled");
return false;
}
else{
return true;
}
});
Try JQuery Validation Engine. Its very easy to implement your form.
Validation Engine
Supported for all browsers
First try adding required to all the necessary fields, like:
<input type="text" class="form-control" id="username" placeholder="Username" required>
Then disable (or delete) the if clause.
If that doesn't work, just let me know in the comments and I'll update the answer.
You are approaching the problem in incorrect way.
On Form submit you need to check each field you want separately.
For example:
$("#form").on('submit', function() {
var submit = true;
$(this).find('span').removeClass('red');
$(this).find('input').each(function() {
if ($.trim($(this).val()) === '') {
submit = false;
$(this).parents('.form-group').find('span').addClass('red');
}
});
return submit;
});

Categories