Img not fading out jQuery - javascript

I'm having some trouble with this JS / Jquery script, it was working completely yesterday, but today, it just wont work properly.
The loading .gif fades in, but just wont fade out...
This is my HTML
...
<div class="banner">
<img src="img/selosiade.png"/><br />
<form>
<input id="username" class="login" type="text" name="username" autocapitalize="off" placeholder="Nome de Usuário"><br />
<input id="password" class="login" type="password" name"password" autocapitalize="off" placeholder="Senha"><br />
<input type="button" value="Login" onClick="login.db();">
<img id="loading" src="img/loading.gif" />
...
(All tags are properly closed)
This what is set to the #loading id.
#loading{
display:none;
z-index:999;
margin-top:5px;
margin-left:50px;
position:absolute;
}
And this is the login.db() script:
var login = {
db: function () {
$('#loading').fadeIn(800, function () {
if (($('#username').val().length === 0) && ($('#password').val().length === 0)) {
$('#user_pass_vazio').fadeIn(800).delay(800).fadeOut(800);
$('#loading').delay(800).fadeOut(800);
} else if ($('#username').val().length === 0) {
$('#user_vazio').fadeIn(800).delay(800).fadeOut(800);
$('#loading').delay(800).fadeOut(800);
} else if ($('#password').val().length === 0) {
$('#pass_vazio').fadeIn(800).delay(800).fadeOut(800);
$('#loading').delay(800).fadeOut(800);
}
var pass1 = $('#password').val();
var pass = CryptoJS.SHA1(pass1);
var user = $('#username').val();
var flag = false;
$.ajax({
url: "http://apt-ghaschel.webatu.com/php/check.php",
type: "POST",
async: false,
data: {
user: user,
pass: pass
},
success: function (msg) {
var b = msg.match(/^.*$/m)[0];
$('#store').text(b);
flag = true;
}
});
if (flag) {
return;
}
b = $('#store').text();
if (b == '1') {
$('#login_certo').fadeIn(800).delay(800).fadeOut(800, function () {
$('div.banner').fadeOut(800, function () {
var encrypted = CryptoJS.AES.encrypt(pass, a);
$.cookie('username', user, {
expires: 365
});
$.cookie('username', encrypted, {
expires: 365
});
window.open("unidades.html?username=" + user + "");
});
});
} else if (b == '2') {
$('#login_errado').fadeIn(800).delay(800).fadeOut(800, function () {});
} else {
$('#erro_desconhecido').fadeIn(800).delay(800).fadeOut(800);
}
});
}
}
Sorry if this is something silly, but I just can figure it out what is wrong.

check whether this will help you, use
$("#loading").stop().fadeOut(800);
instead of
$("#loading").delay(800).fadeOut(800);

The fade out works properly when I disable CryptoJS in your fiddle.
By the way, the login-form div doesn't fade in at the start. I suggest you to use
$(document).ready(function() {
pisca.telalogin();
});

Related

Error stopping function after alert message is shown

I'm developing a proxy service and everything works great. When you press the submit button, it has an onclick function. I also now have it detecting when adblock is enabled, and I don't want the funcion to go through if adblock is detected, (meaning I want it so the proxy won't actually start if you have adblock enabled, and I want the alert message to pop up ONLY when you press the button UNTIL you disable adblock.)
If you have adblock, here's an example of what I'm looking for. (http://fastp.org/) On this website, if you have adblock enabled, you can't submit the form. Mine still goes through after you press "ok" on the alert box. In my javascript code I tried doing a "return false;" and also a "else" but nothing seems to work. I don't want the form to submit if you have adblock enabled.
I want it so if adblock is enabled, it will show the alert box, and when you press "ok" I don't want it to still launch the proxy in the new tab. I want it to launch when adblock is disabled.
Here's my code:
$(document).ready(function() {
$('#browsebtn').click(function() {
val = $('#urlinput').val();
$('#urlinput').val(val.replace($('#remove1').val(), ""));
});
});
$(document).ready(function() {
$('#browsebtn').click(function() {
val = $('#urlinput').val();
$('#urlinput').val(val.replace($('#remove2').val(), ""));
});
});
$(document).ready(function() {
$('#browsebtn').click(function() {
val = $('#urlinput').val();
$('#urlinput').val(val.replace($('#remove3').val(), ""));
});
});
function forceLower(strInput) {
strInput.value = strInput.value.toLowerCase();
}
function checkAdBlocker() {
try {
fetch(
new Request("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js", {
method: 'HEAD',
mode: 'no-cors'
})).catch(error => {
showNotification();
});
} catch (e) {
// Request failed, likely due to ad blocker
showNotification();
}
var x;
x = document.getElementById("urlinput").value;
if (x == "" || x == "https://" || x == "http://" || x == "www." || x == "http://www." || x == "https://www.") {
$("#error").show().delay(3000).fadeOut();
return false;
} else {
var ddl = document.getElementById("servertype");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "server1") {
setTimeout(function() {
window.open('http://server1.com/' + document.getElementById('urlinput').value);
}, 200);
}
if (selectedValue == "server2") {
setTimeout(function() {
window.open('http://server2.com/' + document.getElementById('urlinput').value);
}, 200);
}
if (selectedValue == "server3") {
setTimeout(function() {
window.open('http://server3.com/' + document.getElementById('urlinput').value);
}, 200);
}
if (selectedValue == "server4") {
setTimeout(function() {
window.open('http://server4.com/' + document.getElementById('urlinput').value);
}, 200);
}
}
}
function showNotification() {
alert("Please disable adBlocker");
}
<form action="javascript:void(0);" method="POST">
<input id="remove1" type="hidden" value="https://" /><input id="remove2" type="hidden" value="http://" /><input id="remove3" type="hidden" value="www." />
<input type="text" name="name" placeholder="Enter web address.." id="urlinput" onkeyup="return forceLower(this);" /><button type="submit" id="browsebtn" onclick="return checkAdBlocker()" name="submit" value="Browse">BROWSE</button>
<div class="serverselect"><label>Select Server:</label></div>
<div class="selectserver">
<select id="servertype" name="dropdown">
<option value="server1" data-sort="1">🇺🇸 US Server</option>
<option value="server2" data-sort="2">🇨🇦 CA Server</option>
<option value="server3" data-sort="3">🇩🇪 DE Server</option>
<option value="server4" data-sort="4">🇬🇧 GB Server</option>
</select>
</div>
<p id="error">Please enter a valid URL address.</p>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Sorry, yes I know the code is long, but I wanted to make sure the new code wouldn't affect any code that was left out. (everything is sort of looped together) Thanks for taking a look.
In similar cases I usually use try...catch in while loop as track it with variable:
while (true) {
var adBlocker = false
try {
fetch(
new Request("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js", {
method: 'HEAD',
mode: 'no-cors'
})).catch(error => {
showNotification();
adBlocker = true
});
} catch (e) {
// Request failed, likely due to ad blocker
showNotification();
adBlocker = true
}
if (adBlocker == false) {
break
}
}
UPDATE:
fetch is async function so adBlocker variable is false and the loop is broken before cathing error
In this code I made fetch In async function to be able to use await and call redirect from then method that works on fetch success:
function checkAdBlocker() {
async function AdBlock() {
try {
// Wait for fetch
let adTest = await fetch("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js")
.then(response => {
redirect()
adBlocker = false;
})
.catch(error => {
showNotification();
});
} catch (e) {
// Request failed, likely due to ad blocker
showNotification();
}
}
AdBlock()
function redirect() {
var x;
x = document.getElementById("urlinput").value;
if (x == "" || x == "https://" || x == "http://" || x == "www." || x == "http://www." || x == "https://www.") {
$("#error").show().delay(3000).fadeOut();
return false;
} else {
var ddl = document.getElementById("servertype");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "server1") {
setTimeout(function () {
window.open('https://devoooo-proxy.herokuapp.com/proxy/' + document.getElementById('urlinput').value);
}, 200);
}
if (selectedValue == "server2") {
setTimeout(function () {
window.open('https://google-github.herokuapp.com/http/' + document.getElementById('urlinput').value);
}, 200);
}
if (selectedValue == "server3") {
setTimeout(function () {
window.open('https://proxy.bibliotecavirtualalergia.com/browse.php?u=http://' + document.getElementById('urlinput').value);
}, 200);
}
if (selectedValue == "server4") {
setTimeout(function () {
window.open('http://server3main.epizy.com/browse.php?u=http://' + document.getElementById('urlinput').value);
}, 200);
}
}
}
}

Set cookie using jquery on form submit / log in

Looking for direction or input on something I'm not familiar with. I created a two page site with a log in form that redirects user to the second page with the correct "access code" I created. It works as expected. What I would like to do is set a cookie when user is logged with jquery or vanilla js, then check if the user has logged in before and if they have not redirect back to log in form. I know I have not "tried anything" but just looking to learn and get an idea or advice
HTML:
<form class="form--log-in" id="log-in-form">
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First Name">
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" class="form-control" name="lastName" id="lastName" placeholder="Last Name">
</div>
<div class="form-group">
<label for="userEmail">Email Address</label>
<input type="email" class="form-control" name="userEmail" id="userEmail" placeholder="Email Address">
</div>
<div class="form-group">
<label for="accessCode">Access Code</label>
<input type="text" class="form-control" name="accessCode" id="accessCode" placeholder="Access Code">
</div>
<div class="form--log-in__submit-container">
<button type="submit" class="btn button-submit form--log-in__submit" id="form_submit">
Log in
</button>
</div>
</form>
jquery:
// doc ready
$(function () {
checkCookie();
}
submitHandler: function (form) {
var formData = {
'method': 'register',
'firstName': $('input[name=firstName]').val(),
'lastName': $('input[name=lastName]').val(),
'userEmail': $('input[name=userEmail]').val(),
'accessCode': $('input[name=accessCode]').val(),
};
var validationObj = this;
$.ajax({
type: 'POST',
url: form_submit_endpoint,
data: formData,
success: function (res) {
var parsedResponse = JSON.parse(res);
if (parsedResponse.status === 'success') {
console.log('success');
_siteNS.Utils.setCookie('x-access',true,365);
logInModal();
} else if (parsedResponse.status === 'error') {
validationObj.showErrors({'accessCode': 'Incorrect Access Code.'});
console.log('error');
}
}
})
}
function _readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null;
}
function _setCookie(cookiename, value, numberofdays) {
var d = new Date();
d.setTime(d.getTime() + (numberofdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cookiename + "=" + value + ";" + expires + ";path=/";
}
function checkCookie() {
// set cookie to boolean var
var myCookie = document.cookie === null;
//if the cookie is true and location is not the video page set location to video page
if(myCookie === true && (!location.href.match(/video-page/))){
window.location.replace('video-page');
}
//if the cookie is false and location is not the site root set location to site root
if(myCookie === false && (!location.href.match(/index/))){
window.location.replace('index');
}
}
Here is how you would do it.
After the ajax success, set a localstorage item like 'isLoggedIn', 'true'
In another JS file that is loaded for every page globally, you should check if localstorage flag is set to true.
Redirect to required page based on the result
NOTE: The above method is only to learn about how you can achieve auth. This is definitely not secure. You would have to use some kind of authentication like JWT and set the token in your localhost or cookie that will be sent to the server for each request.
Please do read about authentication before you build a real world app.
$.ajax({
type: 'POST',
url: form_endpoint,
data: formData,
success: function(res) {
var parsedResponse = JSON.parse(res);
if (parsedResponse.status === 'success') {
// set localstorage flag if successfully logged in
// NOTE: this is not secure. You need to have some kind of JWT token to be implemented
if (typeof(Storage) !== "undefined") {
localstorage.setItem('isLoggedIn', 'true');
} else {
// Sorry! No Web Storage support..
}
}
}
});
// In another JS file that is loaded globally
window.on('load', function() {
if (typeof(Storage) !== "undefined") {
const loginStatus = localstorage.getItem('isLoggedIn');
if (loginStatus === 'true') {
// redirect him to logged in page
} else {
// redirect him to unauthorized in page
}
} else {
// Sorry! No Web Storage support..
}
})

Code working in Chrome and Edge but not in IE - setimeout?

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>

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/

JQuery ajax post function is executed at the end of javascript

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);
});
}
});

Categories

Resources