JQuery ajax post function is executed at the end of javascript - 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);
});
}
});

Related

The Verification between email addresses function will not work

I want the user to verify his email address in the "email2" field and in case he has entered the wrong email address the function returns an error message and corrects his email address from the "email" field. This function returns no error but also does not work, ie does not report an error message when email addresses differ. I'm asking for help.
<html>
<script>
function validateForm() {
var x = document.forms["contactform"]["email"].value;
if (x == "") {
alert("E-mail is empty");
return false;
}
var x = document.forms["contactform"]["email2"].value;
if (x == "") {
alert("Verification E-mail is empty");
return false;
if(email != email2){
// Display the error message
document.getElementById("emailMismatch").style.display="inline";
alert("Email address does not match");
return false;
}else{
document.getElementById("emailMismatch").style.display="none";
}
}
}
</script>
<body>
<form name="contactform" method="post">
<input type="text" name="email" maxlength="80" size="30" placeholder="E-mail contact person" title="The e-mail must be in the format, example: primer#email.com ">
<input type="text" name="email2" maxlength="80" size="30" placeholder="Verify E-mail address" title="The e-mail must be in the format, example: primer#email.com ">
<input type="submit" value="Send" style="border:1px solid #000000">
</form>
</body>
</html>
You are missing a } to terminate the second IF so the third IF is inside the second and therefore never runs because it is after a return :)
<script>
function validateForm() {
var x = document.forms["contactform"]["email"].value;
if (x == "") {
alert("E-mail is empty");
return false;
}
var x = document.forms["contactform"]["email2"].value;
if (x == "") {
alert("Verification E-mail is empty");
return false;
} <-- !!!!!!!!!!!!! THIS WAS MISSING !!!!!!!!!!!!
if(email != email2){
// Display the error message
document.getElementById("emailMismatch").style.display="inline";
alert("Email address does not match");
return false;
}else{
document.getElementById("emailMismatch").style.display="none";
}
#} <-- THIS WAS IN THE WRONG PLACE REMOVE IT
}
</script>
You defined a variable named x to hold email input values, then you do comparison with email and email2 variable, which are not defined.
function validateForm() {
var email = document.forms["contactform"]["email"].value;
if (email == "") {
alert("E-mail is empty");
return false;
}
var verificationEmail = document.forms["contactform"]["email2"].value;
if (verificationEmail == "") {
alert("Verification E-mail is empty");
return false;
} <-- !!!!!!!!!!!!! THIS WAS MISSING !!!!!!!!!!!!
if(email != verificationEmail){
// Display the error message
document.getElementById("emailMismatch").style.display="inline";
alert("Email address does not match");
return false;
}else{
document.getElementById("emailMismatch").style.display="none";
}
}

HTML and javascript input and function

I am a new programer in js and I tried to do a basic website using js and html.
I tried to do like username and password input boxes but the function of it doesn't work. What is the problem?
This is the code:
function entering() {
alert("hi")
var username = document.getElementById("fuser");
var password = document.getElementById("fpass");
if (username == "f") {
if (password == "f") {
alert('Nice');
}else {
alert('wrong password');
}else{
alert('wrong username');}}
document.getElementById("frm1").submit();
}
<h1>Best Website</h1>
<h2>Hello!<h2>
<form id = frm1>
Username: <input type = "text" id="fuser"><br>
Password: <input type = "text" id="fpass"><br>
<input type = "button" onclick = "entering()" value = "submit">
</form>
What you are searching for is the value property of the input element.
var username = document.getElementById("fuser");
var password = document.getElementById("fpass");
Are only references to the elements in your page, not what the user entered, for that use
var username = document.getElementById("fuser").value;
var password = document.getElementById("fpass").value;
Complete Code:
function entering() {
alert("hi")
var username = document.getElementById("fuser").value;
var password = document.getElementById("fpass").value;
if (username == "f") {
if (password == "f") {
alert("correct");
} else {
alert("wrong password")
}
} else {
alert("wrong username");
}
//document.getElementById("frm1").submit();
}
<h2>Hello!<h2>
<form id = frm1>
Username: <input type = "text" id="fuser"><br>
Password: <input type = "text" id="fpass"><br>
<input type = "button" onclick = "entering()" value = "submit">
</form>
var username = document.getElementById("fuser");
var password = document.getElementById("fpass");
When grabbing an input element, you get the element stored into a variable, not the value. When you write your if conditional then, you need to point to the property on the element called value.
if (username.value == "f") {
if (password.value == "f") {
You'll need to rework your if/else statements and make sure to access the value of the element you're referencing.
if (username == "f") {
if (password == "f") {
alert('Nice');
}else {
alert('wrong password');
}else{
alert('wrong username');}}
To:
if (username.value == "f") {
if (password.value == "f") {
alert('Nice');
} else {
alert('wrong password');
}
} else {
alert('wrong username');
}
That should get you moving again.
<!DOCTYPE html>
<html>
<head>
<title>The Best Website</title>
</head>
<body>
<h1>Best Website</h1>
<h2>Hello!
<h2>
<form id=frm1>
Username:
<input type="text" id="fuser">
<br> Password:
<input type="text" id="fpass">
<br>
<input type="button" onclick="entering()" value="submit">
</form>
<script>
function entering() {
alert("hi")
var username = document.getElementById("fuser");
var password = document.getElementById("fpass");
if (username == "f") {
if (password == "f") {
alert('Nice');
} else {
alert('wrong password');
}
} else {
alert('wrong username');
}
document.getElementById("frm1").submit();
}
</script>
</body>

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/

html form returning a json array

This is my simple html form that will pass username and password and returns a json array
<form class="form-signin" id="login" method="post" action="/Webservices/0.1/login"">
<input type="text" class="form-control" placeholder="email id" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="password" id= "password">
<button type="submit" name="submit" id="submit" >Sign in</button>
</form>
This is my route:
router.post('/login',function (req,res) {
var email = req.body.email;
var password = req.body.password;
var arrayParam = [];
var emailValidation = emailPattern.test(email);
arrayParam.push('email','password');
reqdParams.verifiyRequiredParameters(arrayParam, req.body, function (result) {
if (result.success == "0") {
res.json(result);
}
else if (email == '' || password == '' ) {
res.json({'success': '0', 'result': {}, 'errorMessage': "data should not be null"});
}
else if (!(emailValidation)) {
res.json({'success': '0', 'result': {}, 'errorMessage': 'not a valid email'});
}
else
{ password =new Buffer(password).toString('base64');
var userObject = {'email':email, 'password': password};
var verifyUserQuery = model.client.prepare("select userId,username,IFNULL(profilePicture,'') as profilePicture,email,password,profileType,IFNULL(profileId,'') as profileId,userType,IFNULL(token,'') as token,deviceName,osType,osVersion,isBlocked,isActive,ofActive,joinedDate from users where email = :email and password=:password");
model.client.query(verifyUserQuery (userObject ),function(err,rows){
if(rows.length> 0){
if(rows[0].isActive == 1){
var userProfile = rows[0];
res.json({'success':'1','result':{'message':'Valid User','userProfile':userProfile},'errorMessage':'No'});
}
else{
res.json({'success':'0','result':{},'errorMessage':'user is not verified'});
}
}
else
res.json({'success':'0','result':{},'errorMessage':'user Invalid'});
});
}
});
});
This code will return a json array:
{"success":"0","result":{},"errorMessage":"user Invalid"}
if success=0 i want to display error Message in html form.
if success-1 i want to redirect to another page.
how to do this?
var err = {"success":"0","result":{},"errorMessage":"user Invalid"},
holder = document.getElementById('errorholder');
if(err.success == '0'){
holder.innerHTML = err.errorMessage;
} else {
// redirect using window.location
}
HTML
<div id="errorholder"></div>

Form validation not working

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.

Categories

Resources