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/
Related
I have the following downloadZip.html. The download works in Chrome and Edge, but not in IE. This file gets called as below from jspf page. When I click "Download listed documents" it call popupDownloadWindow(), which will open downloadZip.html in plainview. This html when loaded calls enableLink() and the flow goes. As the view is plainview, only first if block of enableLink() is executed (if(callerview == "plainview")). Not sure if this is happening because of setTimeout(). Please help me here. Let me know for any information.
function checkReturn(){
//alert('checkReturn - sessionsNotOk global var = '+sessionsNotOk);
if (sessionsNotOk != "DEF") {
var docbases = sessionsNotOk.split(",");
//alert('checkReturn - docbases arr = '+docbases+', length='+docbases.length);
if (docbases.length == 1 && docbases[0] == "OK"){
// All sessions are faja
document.getElementById('divIndicator').style.display='none';
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='none';
document.getElementById('dlink').style.display='inline';
document.getElementById('dlink').style.textAlign='center';
document.getElementById('dlink').style.display='';
} else {
// We need to show the sublogin dialog
var nextDocbase = docbases[0];
//alert("Next NOT AVAILABLE session = "+nextDocbase);
window.opener.$('#subloginmessage').css('display','none');
window.opener.$('#loginIndicator').css('display','none');
window.opener.$('#sub-uid').val(window.opener.$('#user_name').text());
window.opener.$('#sub-uid').attr('disabled','disabled');
window.opener.$('#sub_docbase').text(nextDocbase);
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='inline';
document.getElementById('noSession').style.textAlign='center';
document.getElementById('noSession').style.display='';
window.opener.sublogin_fw = "download";
window.opener.sublogin_db = nextDocbase;
window.opener.$('#sublogindialog').dialog('open');
window.opener.$('#sublogindialog').dialog('option','title','Login to docbase: ' + nextDocbase + ' and click on Download listed documents link again!');
}
return;
}
//Check again in 0.5 second
setTimeout("checkReturn()",500);
//setTimeout(function() {
// checkReturn();
//}, 500);
}
Complete code:
<script>
var downloadZipChildWindow;
function popupDownloadWindow(){
downloadZipChildWindow = window.open('../html/downloadZip.html?view=plainview','downloadwindow','width=300,height=200,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no,resizable=no');
}
</script>
<a id='download_link' class='download_link' href="#" onClick="popupDownloadWindow()">Download listed documents</a>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Download documents as Zip file</title>
<script type="text/javascript" src="../js/jquery-1.6.1.min.js" ></script>
<style type="text/css">
p
{
font-family:"Verdana";
font-size:small;
}
a
{
font-family:"Helvetica";
font-size:small;
}
</style>
<script type="text/javascript">
var lastParam;
var sessionsNotOk = "DEF";
var callerView;
function getParam( paramName )
{
paramName = paramName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+paramName+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
/*
* Checks the return from ajax servlet call "../downloadzip?ask=isSRPsessionsOK&packageIDs="+pIDs".
* Called always right after checkDocbaseSessions() call.
*/
function checkReturn(){
//alert('checkReturn - sessionsNotOk global var = '+sessionsNotOk);
if (sessionsNotOk != "DEF") {
var docbases = sessionsNotOk.split(",");
//alert('checkReturn - docbases arr = '+docbases+', length='+docbases.length);
if (docbases.length == 1 && docbases[0] == "OK"){
// All sessions are faja
document.getElementById('divIndicator').style.display='none';
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='none';
document.getElementById('dlink').style.display='inline';
document.getElementById('dlink').style.textAlign='center';
document.getElementById('dlink').style.display='';
} else {
// We need to show the sublogin dialog
var nextDocbase = docbases[0];
//alert("Next NOT AVAILABLE session = "+nextDocbase);
window.opener.$('#subloginmessage').css('display','none');
window.opener.$('#loginIndicator').css('display','none');
window.opener.$('#sub-uid').val(window.opener.$('#user_name').text());
window.opener.$('#sub-uid').attr('disabled','disabled');
window.opener.$('#sub_docbase').text(nextDocbase);
document.getElementById('checkSession').style.display='none';
document.getElementById('noSession').style.display='inline';
document.getElementById('noSession').style.textAlign='center';
document.getElementById('noSession').style.display='';
window.opener.sublogin_fw = "download";
window.opener.sublogin_db = nextDocbase;
window.opener.$('#sublogindialog').dialog('open');
window.opener.$('#sublogindialog').dialog('option','title','Login to docbase: ' + nextDocbase + ' and click on Download listed documents link again!');
}
return;
}
//Check again in 0.5 second
//setTimeout("checkReturn()",500);
setTimeout(function() {
checkReturn();
}, 500);
}
function enableLink(){
callerView = getParam("view");
var pkgType = "";
var params = "";
var packageIDs = "";
if (callerView == "plainview") {
pkgType = window.opener.$('#hiddenPkgType').attr('value');
// Check available sessions
if (pkgType == 'srp'){
document.getElementById('dlink').style.display='none';
document.getElementById('checkSession').style.display='inline';
document.getElementById('checkSession').style.textAlign='center';
document.getElementById('checkSession').style.display='';
packageIDs = window.opener.$('#hiddenSRPIDs').attr('value');
checkDocbaseSessions(packageIDs);
checkReturn();
}
params = window.opener.$('#hiddenDownloadParams').attr('value');
} else if (callerView == "packagedetailview") {
pkgType = window.opener.$('#hiddenPkgType_DetailedPackageView').attr('value');
if (pkgType == "" || pkgType == null) {
alert("Still loading data, window will be closed. Please click on download button after all data have been loaded on the page!");
window.close();
}
params = window.opener.$('#hiddenDownloadParams_DetailedPackageView').attr('value');
} else if (callerView == "SRP_packagedetailview") {
// Prepare/check remote sessions
packageIDs = window.opener.$('#SRP_DPV_pkgIDs').attr('value');
checkDocbaseSessions(packageIDs);
checkReturn();
pkgType = 'srp';
if (pkgType == "" || pkgType == null) {
alert("Still loading data, window will be closed. Please click on download button after all data have been loaded on the page!");
window.close();
}
params = window.opener.$('#hiddenDownloadParams_SRP_DetailedPackageView').attr('value');
} else if (callerView == "SRP_checkstatusview") {
// Prepare/check remote sessions
packageIDs = window.opener.$('#SRP_CSV_pkgIDs').attr('value');
checkDocbaseSessions(packageIDs);
checkReturn();
pkgType = 'srp';
if (pkgType == "" || pkgType == null) {
alert("Still loading data, window will be closed. Please click on download button after all data have been loaded on the page!");
window.close();
}
params = window.opener.$('#hiddenDownloadParams_SRP_CheckStatusView').attr('value');
}
if (pkgType == 'nlp' || pkgType == 'monnlp') {
document.getElementById('download_zip_stdfilenames_nlp_country').style.display='inline';
document.getElementById('download_zip_stdfilenames_nlp_product').style.display='inline';
document.getElementById('download_zip_stdfilenames_nlp_country').style.textAlign='center';
document.getElementById('download_zip_stdfilenames_nlp_product').style.textAlign='center';
document.getElementById('download_zip_stdfilenames').style.display='none';
} else if (pkgType == 'clp') {
document.getElementById('download_zip_stdfilenames_nlp_country').style.display='none';
document.getElementById('download_zip_stdfilenames_nlp_product').style.display='none';
document.getElementById('download_zip_stdfilenames').style.display='inline';
document.getElementById('download_zip_stdfilenames').style.textAlign='center';
} else if (pkgType == 'ipl') {
document.getElementById('download_zip_stdfilenames_nlp_country').style.display='none';
document.getElementById('download_zip_stdfilenames_nlp_product').style.display='none';
document.getElementById('download_zip_stdfilenames').style.display='inline';
document.getElementById('download_zip_stdfilenames').style.textAlign='center';
}
//Defined as global
zipParamsImp = params + "&filename=import";
zipParamsStd = params + "&filename=standard";
}
function showIndicator(param){
document.getElementById('divIndicator').style.display='inline';
document.getElementById('divIndicator').style.textAlign='center';
document.getElementById('divIndicator').style.display='';
document.getElementById('dlink').style.display='none';
var parameters = "";
if (param == 'import'){
parameters = zipParamsImp;
} else if (param == 'standard') {
parameters = zipParamsStd;
} else if (param == 'standard_nlp_country') {
parameters = zipParamsStd + "_nlp_country";
} else if (param == 'standard_nlp_product') {
parameters = zipParamsStd + "_nlp_product";
}
lastParam = param;
postwith("../downloadzip",parameters);
}
function postwith (to, params) {
var myForm = window.opener.document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
myForm.style.display = 'none';
jQuery.each(params.split('&'), function(){
var pair = this.split('=');
var myInput = window.opener.document.createElement("input") ;
myInput.setAttribute("name", pair[0]) ;
myInput.setAttribute("value", pair[1]);
myForm.appendChild(myInput);
});
var lastInput = window.opener.document.createElement("input") ;
lastInput.setAttribute("name", "download_token_value_id") ;
lastInput.setAttribute("value", "");
myForm.appendChild(lastInput);
window.opener.document.body.appendChild(myForm) ;
myForm.submit();
window.opener.document.body.removeChild(myForm) ;
//setTimeout("checkProgress()",1000);
setTimeout(function(){
checkProgress();
},1000);
}
/*
* Checks return from servlet call "../downloadzip?ask=isready" -> ask whether DownloadAsZipServlet
* has finished its work or not. If finished, close this popup.
*/
function checkProgress(){
window.focus();
$.ajax({
type: "GET",
url: "../downloadzip?ask=isready",
dataType: "text",
//dataType: "script",
//timeout: 2000,
success: function(results)
{
// Normal flow
//var result = eval('('+results+')');
var currParams = window.opener.$('#hiddenDownloadParams').attr('value');
//After closing DPV and clicking on Download Listed Documents button, we have to remove caller param, because there is no caller.
//Caller exists only if openPackage function called, and Download is on a DPV page.
//If we do not remove caller param, then exception occurs.
var callerPrefix = currParams.substring(0,currParams.indexOf('&'));
if (callerPrefix.indexOf('caller=') > -1) {
window.opener.$('#hiddenDownloadParams').attr('value',currParams.replace(callerPrefix+'&',""));
} else {
// No caller param found
}
if (results.indexOf('window.close()') > -1) {
window.close();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
window.top.document.location.href = "../jsp/logout.jsp?msg=Application error (HTTPREQ quicksearch download documents). You have been logged out!";
}
});
}
/*
* In case of SRP - checks whether sessions for all required docbases are available.
* It is needed, because SRP package documents can be located in different docbases.
*/
function checkDocbaseSessions(pIDs){
sessionsNotOk = "DEF";
$.ajax({
type: "GET",
url: "../downloadzip?ask=isSRPsessionsOK&packageIDs="+pIDs,
dataType: "text",
success: function(results)
{
//alert(results);
if ($.trim(results) == 'OK'){
//alert("Sessions are OK!");
sessionsNotOk="OK";
} else {
sessionsNotOk=results;
//alert("Sessions are NOT OK! - "+sessionsNotOk);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
window.top.document.location.href = "../jsp/logout.jsp?msg=Application error (HTTPREQ quicksearch download documents). You have been logged out!";
}
});
}
</script>
</head>
<body style="background-color: #ffffff; font-family: Verdana, Helvetica; font-size: x-small;" onload="enableLink();">
<div id="divIndicator" style="display: none"><br />
<p>Zip file creation in progress. This may take a few minutes, please wait and do not navigate away or start another query!</p>
<br />
<br />
<span id="qIndicator"> <img border="0" src="../img/indicator.gif"></span>
<br />
<br />
</div>
<p style="text-align: center">Download listed documents</p>
<div id="dlink" style="text-align: center">
With import file names
<br />
With standard file names
With standard file names starting with country
With standard file names starting with product
</div>
<div id="noSession" style="display: none">
<p>Some required sessions are unavailable. Please login to the docbase!</p>
</div>
<div id="checkSession" style="display: none">
<p>Checking required sessions in progress. Please wait...</p>
<br />
<span id="qIndicator"> <img border="0" src="../img/indicator.gif"></span>
<br />
</div>
</body>
</html>
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();
}
I have a simple log in and I cannot get the validation to work at all. I was wondering if someone could help.
HTML:
<div class="login">
<h2>Sign In</h2>
<form id="frmLogin" method="post">
Username: <input id="txtUsername" name="txtUsername" type="text" /><br/>
Password: <input name="txtPassword" type="password" /> <br/>
<button onClick="validateLogin()">Log In</button>
</form>
</div><!-- End of Login Section -->
Javascript:
<script>
function validateLogin()
{
var userName = document.getElementsByID('txtUsername').value;
var invalidForm = 0;
if(userName == "")
{
alert("Username cannot be blank!");
invalidForm = 1;
}//end if
if(invalidForm == 0)
{
alert("Form validated, no errors");
}//end if
}
</script>
At the moment I'm just testing for an empty username, once I can get this working I'll continue on with the rest.
Thank you!
To get and element by ID the function name is getElementById and not getElementsByID, besides, javascript is case sensitive so getElementByID does not work.
function validateLogin()
{
var userName = document.getElementById('txtUsername').value;
var invalidForm = 0;
if(userName == "")
{
alert("Username cannot be blank!");
invalidForm = 1;
}//end if
if(invalidForm == 0)
{
alert("Form validated, no errors");
}//end if
}
Do your jquery code something like these :-
<script>
function validateLogin()
{
var userName = document.getElementById('txtUsername').value;
var invalidForm = 0;
var errMessage = ""
if(userName === "")
{
errMessage = "Username cannot be blank!";
invalidForm = 1;
}//end if
if(invalidForm == 0)
{
alert("Form validated, no errors");
}
else if (invalidForm == 1)
{
alert(errMessage);
return false;
}
}
</script>
It may help you.
i have a problem with validating if the username is already taken. I am trying to find out if the username already exists using the "post" method of jquery. But when executing this function, the script is always jumping to the end of the function and is doing the rest of the script first before executing the "post" command. Could you please review my code and help me?
$("#submit").click(function () {
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
var passwort = document.getElementById("passwort").value;
var passwort2 = document.getElementById("passwort2").value;
var validate = false;
checkUsername();
if (validate == true) {
$.post("Login/register.php", {
username: username,
email: email,
passwort: passwort,
passwort2: passwort2,
}, function (info) {
$("#errorBox").empty();
$("#errorBox").html(info);
});
} else {
$('#register').submit(function () {
return false;
});
}
function checkUsername() {
username = document.getElementById("username").value;
// username = replaceUmlauts(username);
if (username.length > 0) {
document.getElementById("username").style.borderColor = "";
// document.getElementById("errorBox").innerHTML =
// "";
validate = true;
checkAvailability();
return false;
} else {
document.getElementById("username").style.borderColor = "red";
document.getElementById("errorBox").innerHTML = "Username muss länger als ein Zeichen sein";
// alert('Username must be longer than one sign');
validate = false;
return false;
}
}
function checkAvailability() {
$.post(
"Login/checkusername.php", {
username: username
},
function (result) {
// if the result is 1
if (result == 1) {
// show that the username is
// available
document
.getElementById("errorBox").innerHTML = "";
return false;
} else {
// show that the username is NOT
// available
document
.getElementById("errorBox").innerHTML = "Username nicht verfuegbar";
document
.getElementById("username").style.borderColor = "red";
validate = false;
return false;
}
});
}
return false;
});
edit: My html code :
<form id="register" >
<div id='registerpopup'>
<div class='close'></div>
<span class='ecs_tooltip'>Schließen mit ESC<span class='arrow'></span></span>
<div id='popup_content'> <!--your content start-->
<table border=0 cellspacing=10 cellpadding=20 align=center>
<div id="errorBox"></div>
<tr>
<th>
<p style="margin-top: 20px; margin-right: 5px">Username:</p>
<p style="margin-top: 18px; margin-right: 5px">E-Mail:<p>
<p style="margin-top: 16px; margin-right: 5px">Passwort:</p>
<p style="margin-top: 16px; margin-right: 5px">Passwort wdhl.:</p>
</th>
<th>
<p style="margin-top: 20px"><input id="username" name="username" type='text' size='30' maxlength='30' ><br></p>
<p><input id="email" name="email" type='text' size='30' maxlength='30'><br></p>
<p><input id="passwort" name="passwort" type='password' size='30' maxlength='30' ><br></p>
<p><input id="passwort2" name ="passwort2" type='password' size='30' maxlength='30'><br></p>
</th>
</tr>
</table>
<table border=0 cellspacing=10 cellpadding=20 align=center>
<tr>
<th>
<button id="submit" class="submit" type="submit" style="margin-top: 30px"> Registrieren </button>
</th>
</tr>
</table>
</div>
</div>
</form>
<script type="text/javascript" src ="js/checkregister.js"></script>
<div class='loader'></div>
<div id='backgroundPopup'></div>
I tried to change the ("#submit") to document.getElementById("submit") to get my code "more clean" but it does not seem to work.
You have a scope issue with your variable validate , I suggest you this in your function checkUsername():
if (username.length > 0) {
document.getElementById("username").style.borderColor = "";
// document.getElementById("errorBox").innerHTML =
// "";
return checkAvailability();
} else {
document.getElementById("username").style.borderColor = "red";
document.getElementById("errorBox").innerHTML = "Username muss länger als ein Zeichen sein";
// alert('Username must be longer than one sign');
return false;
}
, this in your function checkAvailability() :
if (result == 1) {
// show that the username is
// available
document.getElementById("errorBox").innerHTML = "";
return true;
} else {
// show that the username is NOT
// available
document.getElementById("errorBox").innerHTML = "Username nicht verfuegbar";
document.getElementById("username").style.borderColor = "red";
return false;
}
and var validate = checkUsername(); before your if statements in your main function
EDIT : This code is dirty, you should choose working with "old school JS" like document.getElementById for example, or jQuery (ex: $('#myId')), but the use of both is not recommanded
I don't have enough time to clean it all up, but this would be a good start. Pls note that I have used $.post("/echo/html/", { only for the demo purposes and commented the actual line as it wouldn't work in fiddle. Modify the code to suit your needs.
Demo#Fiddle
$("#register").on("submit", function (evt) {
evt.preventDefault();
var $username = $("#username");
var email = $.trim($("#email").val());
var passwort = $.trim($("#passwort").val());
var passwort2 = $.trim($("#passwort2").val());
var $errorBox = $("#errorBox");
var isUser = checkUsername();
if (isUser) {
checkAvailability();
}
function checkUsername() {
var usernameVal = $.trim($username.val());
if (usernameVal.length > 0) {
$username.css({borderColor: "none"});
return true;
} else {
$username.css({borderColor: "red"});
$errorBox.html("Username muss länger als ein Zeichen sein");
}
return false;
}
function checkAvailability() {
//$.post("Login/checkusername.php", {
$.post("/echo/html/", {
"username": $.trim($username.val())
}, function (result) {
// if the result is 1
if (result == 1) {
register().done(function() {
$errorBox.append("<p>Hurray!</p>");
});
} else {
// show that the username is NOT
// available
$errorBox.html("Username nicht verfuegbar");
$username.css({borderColor: "blue"});
return;
}
});
}
function register() {
//return $.post("Login/register.php", {
return $.post("/echo/html/", {
username: $.trim($username.val()),
email: email,
passwort: passwort,
passwort2: passwort2,
}, function (info) {
$errorBox.html(info);
});
}
});
I've just started learning PHP and my teacher recommended I use JS to check the input fields for acording lentgh.
And if the fields are matching specifications to continue with the registration
How do I stop the php from running if RegistrationValidation() returns false ?
Submit button
<input type="button" name="Register" value="Register" onclick="RegistrationValidation()">
Registering the new user
<?php
if (isset($_POST['Register'])) {
include 'SQL.php';
$username = $_POST['username'];
$password = $_POST['password'];
NewUser($username, $password);
} else
echo '';
?>
Javascript function
function RegistrationValidation() {
var username = document.getElementById('username');
var password = document.getElementById('password');
var usererror = document.getElementById('usererror');
var passerror = document.getElementById('passerror');
var registration = document.getElementById('registrationCheck');
var username_check = true;
var password_check = true;
if (username.value.length < 6) {
var username_check = false;
usererror.innerHTML = 'Username must have at least 6 characters.';
} else {
usererror.innerHTML = '';
}
if (password.value.length < 6) {
var password_check = false;
passerror.innerHTML = 'Password must have at least 6 characters.';
} else {
passerror.innerHTML = '';
}
if (username_check == true && password_check == true) {
document.getElementById("myForm").submit();
} else {
return false;
registration.innerHTML = 'Retype username and password';
}
}
//
Your function returns false if the validation failed. So you can simply add an onsubmit handler to the form, using your function as the handler.
// put this before the close </body> tag or wrap it in window.onload = function(){ }
document.getElementById("yourform").onsubmit = RegistrationValidation;
This is better than using a click event on the button because the onsubmit handles other situations, such as the form being submitted via the enter key.
Remember you still need to do the same validation on the PHP side, because the JavaScript validation can easily be circumvented.