Jquery Ajax Form Requires 2 Clicks to submit - javascript

i have an html form which which does jquery/ajax validations.
following is the html form...
<div class="box3">
<form method="post" name="loginform" action="models/login.php">
<h2>LOGIN<br /><br /> (Post/Manage Property)</h2>
<input type="email" class="homepage" name="user_email2" id="user_email2" placeholder="Email" maxlength="50" required />
<div class ="errormsg" id ="errormsg6"></div>
<input type="password" class="homepage" name="user_password2" id="user_password2" placeholder="Password" maxlength="20" required />
<div class ="errormsg" id ="errormsg7"></div>
<input type="submit" name="login" id="login" value="Submit">
<div class ="errormsglast" id ="errormsg8"></div>
<div class="homeforgotpassword">Forgot Password</div>
</form>
</div>
the jquery/ajax for validation is as follows
$(document).ready(function()
{
/* ----------------- Login Validations Global Variables ----------------- */
var user_email2 = "";
var user_password2 = "";
var user_emailajax2 = "";
var user_mobileajax2 = "";
var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
/* ----------------- Define Validate Email */
var validate_email_login = function()
{
var item5 = $("#user_email2").val();
var item5 = item5.toLowerCase();
if (item5.length < 6 || item5.length > 50)
{
$("#errormsg6").html("Email : 6 - 50 Characters");
user_email2 = "";
}
else
{
$("#errormsg6").html("")
user_email2 = item5;
if (!emailformat.test(item5))
{
$("#errormsg6").html("Wrong Email Format")
user_email2 = "";
}
else
{
$("#errormsg6").html("")
user_email2 = item5;
$.ajax(
{
type: 'POST',
url: 'classes/validatelogin.php?f=1',
data: "user_email2=" + item5,
success: function(msg)
{
if (msg == "exists")
{
$("#errormsg6").html("");
user_emailajax2 = item5;
}
else if (msg == "ok")
{
$("#errormsg6").html("Email Does Not Exist");
user_emailajax2 = "";
}
}
});
}
}
}
/* ----------------- Define Validate Password */
var validate_password_login = function()
{
var item5 = $("#user_email2").val();
var item5 = item5.toLowerCase();
var item6 = $("#user_password2").val();
if (item6.length < 8 || item6.length > 20)
{
$("#errormsg7").html("Password : 8-20 Characters")
user_password2 = "";
}
else
{
$("#errormsg7").html("")
user_password2 = item6;
$.ajax(
{
method: "POST",
url: "classes/validatelogin.php?f=2",
data: "user_email2=" + item5 + "&user_password2=" + item6,
success: function(msg)
{
if (msg == "WrongPw")
{
$("#errormsg7").html("Wrong Password");
user_mobileajax2 = "";
}
else if (msg == "CorrectPw")
{
$("#errormsg7").html("");
user_mobileajax2 = "item6";
}
}
});
}
}
/* ----------------- Run Functions */
$("#user_email2").on('focusout', validate_email_login);
$("#user_password2").on('focusout', validate_password_login);
$("#login").on('click', validate_email_login);
$("#login").on('click', validate_password_login);
/* ----------------- Stop on Submit */
$("#login").click(function()
{
if (user_email2 == "" || user_password2 == "" || user_emailajax2 == "" || user_mobileajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)")
return false;
}
else
{
return true;
}
});
});
if there are no errors then the form submits in one click, however if there are errors and these errors are then rectified (as per validation rules) then the submit button requires two clicks to submit.
Have tried the following things
Renaming $("#login").click(function() to $("#login").on( "click", function()
$("#login").trigger("click"); - after return true and before return true
$( "#login" ).click(); - after return true and before return true
<input type="button" name="login" id="login" value="Submit"> - changing the submit to button
I tried this solution (it did not work, result was the same two clicks required... )
$(document).ready(function()
{
/* ----------------- Login Validations Global Variables ----------------- */
var user_email2 = "";
var user_password2 = "";
var user_mobileajax2 = "";
var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
/* ----------------- Define Validate Password */
var validate_password_login = function()
{
// Set up the deferred object
var def = $.Deferred();
var item5 = $("#user_email2").val();
var item5 = item5.toLowerCase();
var item6 = $("#user_password2").val();
if (item6.length < 8 || item6.length > 20)
{
$("#errormsg7").html("Password : 8-20 Characters");
user_password2 = "";
// Not a valid password so reject the deferred
def.reject();
}
else
{
$("#errormsg7").html("");
user_password2 = item6;
$.ajax(
{
method: "POST",
url: "classes/validatelogin.php?f=2",
data: "user_email2=" + item5 + "&user_password2=" + item6
})
.done(function(msg)
{
if (msg == "WrongPw")
{
$("#errormsg7").html("Wrong Password");
user_mobileajax2 = "";
// The server said the PW was wrong, so reject this
def.reject();
}
else if (msg == "CorrectPw")
{
$("#errormsg7").html("");
user_mobileajax2 = "item6";
// Looks like we are valid so we can resolve this
def.resolve();
}
})
.fail(function()
{
// Something went wrong on the server side, so have to reject
def.reject();
});
}
// We return the promise
return def.promise();
}
/* ----------------- Run Functions */
$("#user_password2").on('focusout', validate_password_login);
// Move to submit handler
$('form[name="loginform"]').on('submit', function()
{
// Set up the validation methods inside $.when
$.when(validate_password_login())
.done(function()
{
// Done means success!
return true;
})
.fail(function()
{
// And fail is obviously a fail.
return false;
});
});
});

I didn't fully replicate this with an entire login set up, but I did do a quick fake to test by changing the ajax.success to ajax.error and using a bad url to trigger the error, then inside of the error, I set the msg variable equal to the string that signals a valid response and the form did not require two submits.
That, coupled with giving the code a closer look, I'm going to guess the issue is a sort of race condition due to the ajax calls.
Your click handlers are set up like this:
$("#login").on('click', validate_email_login);
$("#login").on('click', validate_password_login);
$("#login").click(function() { ... });
Inside of that last handler is where the code checks the strings to see if the results are valid. However, by the time it gets to there those previous ajax requests may have not finished loading and those strings probably have not been reset yet. You can add some console.logs in that function to see what those values are and confirm.
Because those ajax calls are asynchronous you are going to have to wait for them to finish before you can check that the form is valid. What you are looking for are Promises and Deferreds.
I would suggest refactoring it into something like this:
Set up a Deferred in both of your validation methods.
Remove the #login click handlers and move everything into a submit handler for the form.
In the submit handler of the form call the validation methods using $.when.
Quick code example:
// Move to submit handler
$('form[name="loginform"]').on('submit', function() {
// Set up the validation methods inside $.when
$.when(validate_email_login(), validate_password_login())
.done(function() {
// Done means success!
return true;
})
.fail(function() {
// And fail is obviously a fail.
return false;
});
});
In addition to the jQuery docs, at a glance, this looks like another good resource for examples and an explanation of everything: http://jqfundamentals.com/chapter/ajax-deferreds. I think the stuff that is most like what you have is towards the bottom.
A quick set up of what one of the validation methods might look like (untested):
var validate_password_login = function() {
// Set up the deferred object
var def = $.Deferred();
var item5 = $("#user_email2").val();
var item5 = item5.toLowerCase();
var item6 = $("#user_password2").val();
if (item6.length < 8 || item6.length > 20) {
$("#errormsg7").html("Password : 8-20 Characters");
user_password2 = "";
// Not a valid password so reject the deferred
def.reject();
} else {
$("#errormsg7").html("");
user_password2 = item6;
$.ajax({
method: "POST",
url: "http://www.google.com",
data: "user_email2=" + item5 + "&user_password2=" + item6
})
.done(function(msg) {
if (msg == "WrongPw") {
$("#errormsg7").html("Wrong Password");
user_mobileajax2 = "";
// The server said the PW was wrong, so reject this
def.reject();
} else if (msg == "CorrectPw") {
$("#errormsg7").html("");
user_mobileajax2 = "item6";
// Looks like we are valid so we can resolve this
def.resolve();
}
})
.fail(function() {
// Something went wrong on the server side, so have to reject
def.reject();
});
}
// We return the promise
return def.promise();
}

Related

Jquery Ajax On-Focusout On-Submit - Requires 2 Clicks

Hello I have a jquery and ajax validation form, when you fill the values (wrong values) x#x.com and 1111111 in password it will give ajax validation notice (which is fine) but after that if you put in the values (correct values) example#example.com and 12345678 it requires two clicks to submit. Meaning if you put wrong values first and then put correct values then it will require two clicks to submit. following is the code. I have set the code below so you can copy and paste the code into files (filenames given before) and you will have a working model to work with. I have hardcoded the php validate file so you guys can copy and paste the code and see how it works.
index.php
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
</head>
<body>
<form method="post" name="loginform" action="success.php">
<input type="email" class="homepage" name="user_email2" id="user_email2" placeholder="Email" maxlength="50" required />
<div class ="errormsg" id ="errormsg6"></div>
<input type="password" class="homepage" name="user_password2" id="user_password2" placeholder="Password" maxlength="20" required />
<div class ="errormsg" id ="errormsg7"></div>
<input type="submit" name="login" id="login" value="Submit">
<div class ="errormsglast" id ="errormsg8"></div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="validatelogin.js"></script>
</body>
</html>
validatelogin.js
$(document).ready(function()
{
/* ----------------- Login Validations Global Variables ----------------- */
var user_email2 = "";
var user_emailajax2 = "";
var user_password2 = "";
var user_passwordajax2 = "";
var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
/* ----------------- Define Validate Email */
var validate_email_login = function()
{
var item5 = $("#user_email2").val();
var item5 = item5.toLowerCase();
if (item5.length < 6 || item5.length > 50)
{
$("#errormsg6").html("Email : 6 - 50 Characters");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
if (!emailformat.test(item5))
{
$("#errormsg6").html("Wrong Email Format");
user_email2 = "";
}
else
{
$("#errormsg6").html("");
user_email2 = item5;
$.ajax(
{
type: 'POST',
url: 'validatelogin.php?f=1',
data: "user_email2=" + item5,
success: function(msg)
{
if (msg == "ok")
{
user_emailajax2 = "";
$("#errormsg6").html("Email Does Not Exist");
}
else if (msg == "exists")
{
user_emailajax2 = item5;
$("#errormsg6").html("");
}
}
});
}
}
}
/* ----------------- Define Validate Password */
var validate_password_login = function()
{
var item5 = $("#user_email2").val();
var item5 = item5.toLowerCase();
var item6 = $("#user_password2").val();
if (item6.length < 8 || item6.length > 20)
{
$("#errormsg7").html("Password : 8-20 Characters");
user_password2 = "";
}
else
{
$("#errormsg7").html("");
user_password2 = item6;
if (user_email2 != "" && user_emailajax2 != "")
{
$.ajax(
{
method: "POST",
url: "validatelogin.php?f=2",
data: "user_email2=" + item5 + "&user_password2=" + item6,
success: function(msg)
{
if (msg == "WrongPw")
{
user_passwordajax2 = "";
$("#errormsg7").html("Wrong Password");
}
else if (msg == "CorrectPw")
{
user_passwordajax2 = item6;
$("#errormsg7").html("");
/* window.location.href="manage-properties"; */
}
}
});
}
}
}
/* ----------------- Run Functions */
$("#user_email2").on('focusout', validate_email_login);
$("#user_password2").on('focusout', validate_password_login);
$("#login").on('click', validate_email_login);
$("#login").on('click', validate_password_login);
/* ----------------- Stop on Submit */
$("#login").on('click', function()
{
if (user_email2 == "" || user_emailajax2 == "" || user_password2 == "" || user_passwordajax2 == "")
{
$("#errormsg8").html("Please Fill All Fields (Correctly)");
console.log("submit false");
return false;
}
else
{
$("#errormsg8").html("");
console.log("submit true");
return true;
}
});
});
validatelogin.php
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if($_GET['f']==1) {
if(isset($_POST['user_email2'])) {
$user_email2 = strtolower($_POST['user_email2']);
if($user_email2 == "example#example.com") {
echo "exists";
} else {
echo "ok";
}
}
}
if($_GET['f']==2) {
if(isset($_POST['user_email2'], $_POST['user_password2'] )) {
$user_email2 = strtolower($_POST['user_email2']);
$user_password2 = $_POST['user_password2'];
if($user_email2!="example#example.com" and $user_password2!="12345678") {
echo "WrongPw";
} elseif($user_email2=="example#example.com" and $user_password2=="12345678") {
echo "CorrectPw";
}
}
}
?>
success.php
<?php
echo "Login Successful";
?>
Tried Solutions
1. Putting a delay on the submit button
2. On Keyup instead of on Focusout (this works but not what is required)
3. Give delay to keyup (could not get it to work with ajax - but its closer to what I require, but not exactly what I require
4. Triggering the click on submit on return true of ajax (also did not work)
I need some javascript expert to look into it and give me solution.
Okay, I don't want to be rude, but all that code is a bit of a disaster. You're calling the on click function 3 different times, you're making ajax calls to the server on every form change and on submit. Then you're actually making two separate ajax calls for the actual submit function.
The code below is a lot more compact, only ever makes one ajax call and should work. I'll explain a bit before each code block
Your form add an id so that jQuery can use serialize in the ajax call
<form method="post" id="loginform" name="loginform" action="success.php">
<input type="email" class="homepage" name="user_email2" id="user_email2" placeholder="Email" maxlength="50" required />
<div class ="errormsg" id ="errormsg6"></div>
<input type="password" class="homepage" name="user_password2" id="user_password2" placeholder="Password" maxlength="20" required />
<div class ="errormsg" id ="errormsg7"></div>
<input type="submit" name="login" id="login" value="Submit">
<div class ="errormsglast" id ="errormsg8"></div>
</form>
validatelogin.php - This should only be one call to the server, do both functions in one, return the data as json rather than echoing single values, that way you get an object back that you can parse in your jQuery code.
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_POST['user_email2'], $_POST['user_password2'] )) {
$user_password2 = $_POST['user_password2'];
$user_email2 = strtolower($_POST['user_email2']);
if($user_email2 != "example#example.com") {
$data['email_check'] = 'false';
} else {
$data['email_check'] = 'true';
}
$data = array;
if($user_email2!="example#example.com" && $user_password2!="12345678") {
$data['password_check'] = 'false';
} else {
$data['password_check'] = 'true';
}
}
print(json_encode($data));
jQuery - I am not really sure why you're calling all these functions on blur and the multiple on clicks. Just do it in the one on click, call validate email, if that passes you move on to validate password and if that passes it makes the ajax call to actually check the details against the server.
Also avoid variable names like item5, errormsg6, to another developer that means nothing, and it won't to you in 6 months either. And don't tell people which element was wrong, ie "Incorrect password" just for security, just tell them their login details are wrong.
$(document).ready(function() {
/* ----------------- Login Validations Global Variables ----------------- */
var user_email2 = "";
var user_emailajax2 = "";
var user_password2 = "";
var user_passwordajax2 = "";
var emailformat = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
/* ----------------- Define Validate Email */
var validate_email_login = function() {
var email = $("#user_email2").val().toLowerCase();
var errors = [];
if (email.length < 6 || email.length > 50) {
errors.push("Email : 6 - 50 Characters<br>");
}
if (!emailformat.test(email)) {
errors.push("Wrong Email Format");
}
if( errors.length > 0 ) {
$("#errormsg6").html(errors);
return false;
}
$("#errormsg6").html();
validate_password_login();
}
/* ----------------- Define Validate Password */
var validate_password_login = function() {
var item6 = $("#user_password2").val();
if (item6.length < 8 || item6.length > 20) {
$("#errormsg7").html("Password : 8-20 Characters");
return false;
}
$("#errormsg7").html("");
submitForm();
}
var submitForm = function() {
$.ajax({
type: 'POST',
url: 'validatelogin.php',
dataType: "json",
data: $("#loginform").serialize(),
success: function(msg) {
if(msg.email_check == 'true' && msg.password_check == 'true') {
//do whatever it is you want to do on correct login here
} else {
$("#errormsg6").html("Your login details are incorrect, please check and try again");
}
}
});
}
/* ----------------- Stop on Submit */
$("#login").on('click', function() {
errors = [];
if(validate_email_login() == true) {
alert("hi");
}
});
});
You can see the error validation on the jQuery end here: https://jsfiddle.net/calder12/3fhvpenr/

How to return false from a main function after an ajax callback?

I perform an edit to ensure against duplicate emails by making an ajax call and supplying a callback. If a duplicate exists, I want to return false from submit event. Is there an elegant way to achieve this without setting async=false? What I tried (see emailCallback) is not working.
submit event
EDIT (included the rest of the submit handler).
$("#form-accounts").on("submit", function (e) {
e.preventDefault();
if (!$(this).get(0).checkValidity()) return false;
if (!customValidation(true, false)) return;
checkDupEmail(emailCallback);
function emailCallback(result) {
if (result) return (function () { return false } ());
}
if ($("#submit").text() == "Create Account") {
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/accounts.php', formData + "&action=create-account", createSuccess);
function createSuccess(result) {
if (isNaN(result)) {
showMessage(0, result);
return;
}
localStorage.setItem("account-id", result);
debugger
setUsertype($("input[name=user-type]:checked").val());
showMessage(1, "Account Created");
};
return
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
};
var anRandom = randomString(14, rString);
$("#code").val(anRandom);
console.log("v-code=" + anRandom);
$("#submit").css({ 'display': 'none' });
$("#verify").css({ 'display': 'block' });
var subject = "Writer's Tryst Verification Code"
$("#subject").val(subject);
var msg = "This mail is intended for the person who requested verification of email ownership at Writers-Tryst (" + getWriterTrystURL() + ").\n\n" + "Double click on the code below and then copy it. Return to our website and and paste the code.\n\nYour verification code: \n\n" + anRandom;
$("#msg").val(msg);
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/sendmail.php', formData, successMail, "create-account error: ");
function successMail(result) {
$("#ver-email-msg").val("An email has been sent to you. Double-click the verification code then copy and paste it below.").css({ 'display': 'block' });
}
});
function checkDupEmail(callback) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, emailSuccess);
function emailSuccess(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
callback(true);
} else callback(false);
}
}
Instead of passing a callback, why don't you just submit the form when your Ajax call completes successfully?
$("#form-accounts").on("submit", function (e) {
// Always cancel the submit initially so the form is not submitted until after the Ajax call is complete
e.preventDefault();
...
checkDupEmail(this);
...
});
function checkDupEmail(form) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, function(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
} else {
form.submit();
}
}
}
A better approach than that would be to submit your form using Ajax. That would eliminate the need for two calls to the server.

Return false is not prevent calling form submitting in javascript

On a form submit I am calling following function.
function confirmSubmit() {
var checkedAtLeastOne = false;
var checkboxs = document.getElementsByName("reportColumns");
var reportId = $('#reportId').val();
console.log(checkboxs.length);
for(var i = 0, l = checkboxs.length; i < l; i++) {
if(checkboxs[i].checked) {
checkedAtLeastOne = true;
break;
}
}
if(checkedAtLeastOne) {
if(!reportId) {
alert('Report ID cannot be empty');
return false;
} else {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "checkreportid.action?reportId=" + reportId, true);
xhttp.send();
xhttp.onreadystatechange = function (e) {
if(xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("checkreportid").innerHTML = xhttp.responseText;
var reportid = $('#reportid').val();
console.log("reportId->" + reportId);
console.log("reportid->" + $('#reportid').val());
if(reportid == reportId) {
alert("Duplicate Report ID!");
return false;
} else {
return true;
}
}
}
}
} else {
alert("You must select atleast one column");
//e.preventDefault();
return false;
}
}
Here if the reportid equals to reportId it gives the alert (Duplicate Report ID) but it calls the action. return false is not prevent calling the action.
I am calling the function as below.
<s:form action="savereport" namespace="/" validate="true"
onsubmit="return confirmSubmit()">
EDITED
Now I am trying following. If the report ID is empty it gives relevant alert message (Report ID cannot be empty). It it is not empty it calls the checkreportid action but it doesn't give duplicate error message even if there are duplicate report ids. It calls the form submitting action.
function confirmSubmit() {
var checkedAtLeastOne = false;
var checkboxs = document.getElementsByName("reportColumns");
var reportId = $('#reportId').val();
console.log(checkboxs.length);
for (var i = 0, l = checkboxs.length; i < l; i++) {
if (checkboxs[i].checked) {
checkedAtLeastOne = true;
break;
}
}
if (!reportId) {
alert('Report ID cannot be empty');
return false;
} else {
////////
$.ajax({
url: "<s:url action='checkreportid'/>",
type: "GET",
data: {reportId: reportId},
dataType: "text/javascript",
traditional: true,
statusCode: {
200: function (data) {
console.log(data.responseText);
document.getElementById("checkreportid").innerHTML = data.responseText;
var reportid = $('#reportid').val();
console.log("reportId->"+reportId);
console.log("reportid->"+reportid);
if (reportid==reportId) {
alert("Duplicate Report ID!");
return false;
} else {
if (!checkedAtLeastOne) {
return true;
} else {
alert("You must select atleast one column");
return false;
}
}
}
}
});
}
}
What am I missing with my code ?
This is due to the asyncronous nature of a XMLHttpRequest. You are returning false in a callback function, not in the onsubmit handler.
You should look into doing what you want without an XMLHttpRequest or use a syncronous request (this is not reccomended and disabled in some browsers).
The reccomended option is to stop the form submitting all the time with
e.preventDefault();
return false;
And to manually submit the form with a XMLHttpRequest in the original callback if you want to.
The reason is that XMLHttpRequest is aysnchronous.
Your call to
xhttp.send();
returns immediately and therefore that if-else branch doesn't have a return false.
The return statements in your code boil down to:
if(checkedAtLeastOne) {
if(!reportId) {
return false;
} else {
}
} else {
return false;
}
You should add preventDefault method to the form element like below.
<form onsubmit='event.preventDefault(); return confirmSubmit();'>
<input type='submit' />
</form>
Use return in onsubmit event to trigger return false action,
<form onsubmit = "return confirmSubmit()">
</form>

Custom-validated form won't submit

I wrote a script which allows me to validate a form with my Zend_Form validators instead of a classic client-side validation (like jQuery Validate) + server-side validation.
$(document).ready(function() {
var form = $('form'); // target form
var requests = [], validations = [];
var nbInputs = $('input[type="text"], input[type="password"]').length; // number of inputs (text/password) in the form
var cancelSubmit = true;
form.submit(function() {
// if we call the submit inside the function, skip validation
if(cancelSubmit === false) {
console.log('[-] cancelSubmit is false. Validation skipped.');
return true;
}
console.log('[-] Entering validation');
// resetting requests and validations results
requests.length = 0;
validations.length = 0;
// for each input (text/password), get the validation status from the server
$('input[type="text"], input[type="password"]').each(function(i) {
var validatorField = $(this).attr('data-validator');
var valueField = $(this).val();
postData = {
validator: validatorField,
value: valueField
};
// storing requests into an array
requests.push($.post('/validate', postData));
});
(function($) {
$.whenAll = function() {
return $.when.apply($, arguments);
};
})(jQuery);
// when all the requests are done and returned a response
$.whenAll(requests).then(function() {
// show the validation status for each input
$.each(requests, function(i, element) {
element.done(function(data) {
json = $.parseJSON(data);
formGroup = $('input:eq('+i+')').parent();
// if it isn't valid, show error
if(json.valid == 0) {
if($('span.help-block', formGroup).length == 0) {
$(formGroup).addClass('has-error').append('<span class="help-block">'+json.message+'</span>');
$('label', formGroup).addClass('control-label');
}
// and store the validation status
validations.push(0);
}
// else, remove error
else if(json.valid == 1) {
$(formGroup).removeClass('has-error');
$('.help-block', formGroup).remove();
// and store the validation status
validations.push(1);
}
// if we got all the validations required
if(validations.length == nbInputs)
{
console.log('[-] All validations have been done.');
if($.inArray(0, validations) == -1){
console.log('[-] No errors. Submitting form.');
cancelSubmit = false;
form.submit();
}
else
console.log('[-] There are still errors.');
}
});
});
});
return false;
});
});
The validation page server-side send a JSON : { valid: 0, message: "error message" } or { valid: 1}.
I can't have the form to be submitted. When I enter valid values, it does skip validation, but don't submit the form. I have to hit the submit button again to make it work (but, I could have entered non-valid values that wouldn't be checked in this time, as cancelSubmitis set to false).
Isn't return true; supposed to submit the form when used inside a .submit() ?

How to stop execution when form validation in javascript

I have two questions from the coding below.
First, now i would like to perform validation before submission. How can I stop submission if some errors are detected from the validation function? Is it simply return false after each of the error msg? however, it seems still check all fields instead of stopping after getting one error.
Second, i would like to insert the data via php. Everytime, it can successfully add the data to the database, however, it always alert "Error: error". I dunno where does the error come from...
$(document).ready(function()
{
$('#test').click(function(){
validation();
});
function validation(){
var loginID=$("#loginID").val();
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
}
else
{
}
// check pw
$("#errorPW").hide();
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
}
else
{
}
//return false;
} // end of #validation
$('form').submit(function(){
validation();
$.ajax({
type: 'POST',
data:
{
loginID: $("#loginID").val(),
// some data here
},
url: 'http://mydomain.com/reg.php',
success: function(data){
alert('successfully.');
},
error: function(jqXHR, textStatus){
alert("Error: " + textStatus);
}
});
return false;
});
});
you can use return false.It will stop the execution
<form onSubmit="validatdeForm();"></form>
function validatdeForm()
{
//here return true if validation passed otherwise return false
}
or
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
return false;
}
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
return false;
}
it should be something like below. return false stop execution of script when error is there.
function validation(){
var loginID=$("#loginID").val();
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
return false;
}
else
{
return true;
}
// check pw
$("#errorPW").hide();
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
return false;
}
else
{
return true;
}
return true;
} // end of #validation
Design your validation function as below,
function validation()
{
var isValid = true;
if(field validation fail)
{
isValid = false;
}
else if(field validation fail)
{
isValid = false;
}
return isValid;
}
basic idea behind code is to returning false whenever your validation fails.
To make a proper form validation, I will suggest you go about doing it in a more organized way. It is easier to debug. Try this:
var validation = {
// Checking your login ID
'loginID' : function() {
// Login ID validation code here...
// If a validation fails set validation.errors = true;
// Additionally you can have a validation.idError that contains
// some error message for an id error.
},
// Checking your password
'loginPW' : function() {
// Password validation code here...
// If a validation fails set validation.errors = true;
// As with id, you can have a validation.pwError that contains
// some error message for a password error.
},
'sendRequest' : function () {
if(!validation.errors) {
// Code for whatever you want to do at form submit.
}
}
};
$('#test').click(function(){
validation.errors = false;
validation.loginID();
validation.loginPW();
validation.sendRequest();
return false;
});
function validateimage() { if($("#photo").val() !== '' ) {
var extensions = new Array("jpg","jpeg","gif","png","bmp");
var image_file = document.form_useradd.photo.value;
var image_length = document.form_useradd.photo.value.length;
var pos = image_file.lastIndexOf('.') + 1;
var ext = image_file.substring(pos, image_length);
var final_ext = ext.toLowerCase();
for (i = 0; i < extensions.length; i++)
{
if(extensions[i] == final_ext)
{
return true;
}
}
alert(" Upload an image file with one of the following extensions: "+ extensions.join(', ') +".");
//$("#error-innertxt_photo").show().fadeOut(5000);
//$("#error-innertxt_photo").html('Enter valid file type');
//$("#photo").focus();
return false;
}

Categories

Resources