Best code practice for javascript if-then-else - javascript

I'm looking for javascript and jquery experts to set me on the right path. I have the following code and I noticed that before the functions are completed the code passes through the focus() and return false; and again once the function comes back false; Will someone show me the proper way to write this code. Thanks!
// validate passwords
if(!VerifyPassword($("#CurrentPassword").val())) {
$("#CurrentPassword").focus();
return false;
}
if($("#NewPassword").val() != "") {
if(!ValidatePassword($("#NewPassword").val())) {
$("#NewPassword").focus();
return false;
}
if($("#NewPassword").val() != $("#RetypePassword").val()) {
alert("The new password is not the same as the retyped password");
return false;
}
}
function ValidatePassword(password) {
if(password.length < 6) {
alert("Password must contain at least six characters!");
return false;
}
re = /[0-9]/;
if(!re.test(password)) {
alert("Password must contain at least one number (0-9)!");
return false;
}
re = /[a-z]/;
if(!re.test(password)) {
alert("Password must contain at least one lowercase letter (a-z)!");
return false;
}
re = /[A-Z]/;
if(!re.test(password)) {
alert("Password must contain at least one uppercase letter (A-Z)!");
return false;
}
return true;
}
function VerifyPassword(password) {
urlString = "../sql/db_verify_password.php?Password=" + password;
/* send calendar updated information and return status message */
$.ajax({
type: "GET",
url: urlString,
dataType: "xml",
success: function(xml) {
$(xml).find('Results').each(function() {
var status = $(this).find('Status').text();
if(status != "OK") {
alert(status);
return false;
}
});
}
});
}

Let's see what happens in your code!
You first call
VerifyPassword($("#CurrentPassword").val())
which leads to
$.ajax({
//content omitted
});
Now, the first a in ajax stands for asynchronous. This means a request for some other resource will be made, but you won't wait until the request is finished (if you wait you would call it synchronous).
Instead, your code execution continues, setting the focus on the input and returning false.
Finally, when the request finishes and returns, then the function you specified in success: will be executed!
Knowing this you want to change the focus within the function specified in success::

Related

javascript validation and ajax call simultaneously not working

I have code in that javascript and ajax call need to be work simultaneously. But it did not work. And always go to return true.
Functionality of create function is validation of data and ajax call which execute query and depend on result it will further execute. If response text is yes then it call confirmval function. And then further it ask for confirmation and next execution But I face problem is function not return false it always go to true. I cant understand why this happening?
function create()
{
if (document.companyregister.cmpname.value === "")
{
alert("Please Enter Company name");
document.companyregister.cmpname.value = "";
document.companyregister.cmpname.focus();
return false;
}
var companyname = document.companyregister.cmpname.value;
var username = document.companyregister.username.value;
$.ajax({
url: 'checkexisting.php',
type: 'POST',
data: {companyname: companyname,username:username},
success: function(errorResponse) {
var result = errorResponse.trim();
if(result=="yes"){
return confirmval(companyname,username);
}
else{
document.getElementById("formsubmitting").style.display = "block";
document.getElementById("hidesubmit").style.display = "none";
return true;
}
}
});
}
function confirmval(companyname,username){
var c = confirm("This company is already created.\nWould you like to delete existing company?");
if(c){
alert("c");
$.ajax({
url: 'updatecompany.php',
type: 'POST',
data: {companyname: companyname,username:username},
success: function(responsetext) {
var result = responsetext.trim();
if(result=="yes"){
document.getElementById("formsubmitting").style.display = "block";
document.getElementById("hidesubmit").style.display = "none";
return true;
}
}
});
}
else{
alert("notc");
window.location="http://www.google.com";
}
}
You are trying to return two values after your first ajax call:
if(result=="yes"){
return confirmval(companyname,username);
return false;
}
This will just return the result of confirmval function (which appears to always return true), and the 'return false' line will never be run, thus it will always return true.
If you need that result=="yes" to return false, I might recommend something like:
if(result=="yes"){
var confirmvalResult = confirmval(companyname,username);
if(confirmvalResult) {
return false;
} else {
// not sure what you want to do here
}
}

JQuery: Why is empty? [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I'm creating a form and I want to validate it in real time. Everythings works in the ajax call, but I have a problem with the returns.
This is the code:
function checkEmail() {
var reg_exp = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
var mail = $("#email").val();
if (!reg_exp.test(mail) || (mail === "") || (mail === "undefined")) {
$("#mail_mess").html("Enter a valid email address");
return false;
}
else {
var r = '';
$.ajax({
type: "POST",
url: "index.php?p=jsform&ajaxcall=checkEmail",
data: {'mail':mail},
dataType: 'json',
success: function(res) {
r = res;
if(res) {
$("#mail_mess").html("OK");
//return true;
}
else {
$("#mail_mess").html("Email already Exists!");
//return false;
}
}
});
//alert(r);
return r;
}
}
$("#email").on("input", function() {
checkEmail();
});
$("#submitButton").click(function() {
if(... && checkEmail()) {
sendForm();
}
else {
$("#form_message").html("<span class='error'>All fields are required</span>");
}
});
As you can see, I call the function checkEmail() on input change (for the realtime validation) and on submit (all fields check before sending data).
The function checkEmail() should return false on invalid email or on already existing email and should return true on valid and non existing email.
Now.. the function works on realtime validation, I get the "non valid", "already exists" or "valid" exactly when I want. The problem is with the returns, because when I return r, it is an empty string (seems like r = res doesn't work).
And if I try to uncomment the returns inside the if(res)/else they don't work as well.
I'm sorry about my bad english! Thanks for any help :-)
checkMail should accept an optional callback, and call it with the result if defined
function checkEmail(callback) {
var reg_exp = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
var mail = $("#email").val();
if (!reg_exp.test(mail) || (mail === "") || (mail === "undefined")) {
$("#mail_mess").html("Enter a valid email address");
if(callback) {
callback(false);
}
}
else {
$.ajax({
type: "POST",
url: "index.php?p=jsform&ajaxcall=checkEmail",
data: {'mail':mail},
dataType: 'json',
success: function(res) {
if(res) {
$("#mail_mess").html("OK");
//return true;
}
else {
$("#mail_mess").html("Email already Exists!");
//return false;
}
if(callback) {
callback(res);
}
}
});
}
}
no need for callback function here
$("#email").on("input", function() {
checkEmail();
});
the fail function defined to avoid repetition because there's now two "false" paths
$("#submitButton").click(function() {
function fail() {
$("#form_message").html("<span class='error'>All fields are required</span>");
}
if(...) {
checkEmail(function(r) {
if (r) {
sendForm();
}
else {
fail()
});
else {
fail();
}
});

JavaScript Form Validate - "False" not working as needed

I am trying to evaluate a form text/email field to see if there is something there and if so, run it past a regular expression valuation. It worked fine when I included the regex code in the SendEmail function with the rest of the logic but when I tried to move the regex part out into it's own function(validateEmailAddress), the validation still works but it doesn't seem to want to return false and just stop. Instead it continues on to the ajax part and sends the email regardless of whether it passes the regex test or not. It's the same code so I'm not sure why the "return false" doesn't work once the regex piece is moved out into it's own function.
Any thoughts are appreciated and THANK YOU!
function validateEmailAddress(address) {
filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (!filter.test(address)) {
alert(address + ' - Is an invalid email address.');
return false;
}
}
function SendEmail() {
var emailFromVal = document.getElementById("EmailFrom").value;
var emailToVal = document.getElementById("EmailTo").value;
if (emailFromVal != 0) {
validateEmailAddress(emailFromVal);
} else {
alert("Please provide your email address.");
return false;
}
if (emailToVal != 0) {
}
else {
alert("Please provide your friend's email address.");
return false;
}
$.ajax({
method: 'POST',
url: '/_ajax/emailshare/',
dataType: 'json',
data: formCollection,
success: function (data) {
///send that email out
}
});
}
You are not doing anything with the return value from validateEmailAddress(), try this:
if (emailFromVal != 0) {
if(!validateEmailAddress(emailFromVal)){
return false;
}
} else {
alert("Please provide your email address.");
return false;
}
also, you need to return true from validateEmailAddress() when the email is valid:
function validateEmailAddress(address) {
filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (!filter.test(address)) {
alert(address + ' - Is an invalid email address.');
return false;
}
return true;
}
return false; in validateEmailAddress will return just from validateEmailAddress, not from the enclosing function (SendEmail).
Your options are:
Check the return value of validateEmailAddress from the enclosing
function:
if(!validateEmailAddress(address)) return false;
OR
Throw from validateEmailAddress and catch the error from the
enclosing function (this'll allow the error to propagate up the
stack to an arbitrary length until you catch it--i.e., you don't
have to catch just from the enclosing function but also from its
caller or it's caller's caller, and so on and so forth).

AJAX "success" executing before response is returned

I'm hoping this is just a simple fix due to me being a little dumb somewhere along the line. I'm executing my ASP.NET MVC login using AJAX. There is a "success" handler which returns a "true" value to the calling function which, in turn, load the home page.
The issue is that the "success" handler is executing BEFORE any value is returned - which means that nothing happens because the value is not "SUCCESS". I can confirm this by looking at the request in Firebug, the value returned is SUCCESS but nothing happens. If I apply a breakpoint to the end of the function and then continue execution it works just fine.
I have no idea what the issue is, I'd be very grateful for help or an explanation to what I'm doing wrong.
Thanks!
My JS Function:
function LogIn(UserName, Password) {
var Cont = true;
var ErrorString = "";
if (UserName == null || UserName == "") {
Cont = false;
ErrorString += "Username is Required.";
}
if (Password == null || Password == "") {
Cont = false;
ErrorString += "Password is Required.";
}
var result = false;
if (Cont) {
var LogInUrl = "/AJAX/LogIn?UserName=" + UserName + "&Password=" + Password;
$.ajax({
url: LogInUrl,
type:"GET",
success: function( data ){
if (data == "SUCCESS") {
result = true;
}
}
})
}
return result;
}
UPDATE: The function that calls the LogIn function:
$('#FormLogin').submit(function (e) {
e.preventDefault();
var UserName = $("#TxtLoginUsername").val();
var Password = $("#TxtLoginPassword").val();
var IsLoggedIn = LogIn(UserName, Password);
if (IsLoggedIn) {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
})
As I said, the function does it's job and logs me in, but the "success" handler seems to execute before the value is returned.
Change your ajax call to something like this:
$.ajax({
url: LogInUrl,
type:"GET",
success: function( data ){
if (data == "SUCCESS") {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
}
});
There is no point in returning result from LogIn, it'll always be false. You need to put the code handling the returned value in the callback.
Another alternative, if you don't like the idea of your LogIn function being so closely coupled to DOM manipulation is to return the promise from your ajax call. So at the end of LogIn, you'd do something like this:
return $.ajax({
url: LogInUrl,
type:"GET"
}
});
And then when you call it, you'd do something like this:
LogIn(UserName, Password).then(function(data) {
if (data == "SUCCESS") {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
});

Javascript If statement evaluation not working correctly [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
So this is my code for some ajax that I'm doing.
function check_password(){
var username = $("#username").val();
if(username.length > 0){
var bool = -1;
$('#Loading2').show();
$.post("check_login.php", {
username: $('#username').val(),
password: $('#password').val(),
},
function(response) {
$('#Info2').fadeOut(500);
$('#Loading2').hide();
bool = response.indexOf('success');
setTimeout("finishAjax('Info2', '"+escape(response)+"')", 450);
$('#password').after(bool);
return response.indexOf('success');
});
}
}
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn(750);
}
and here I'm trying to handle the return value from the check password function.
jQuery(function() {
$("#submitl").click(function(){
$(".error").hide();
var hasError = false;
var passwordVal = $("#password").val();
var username = $("#username").val();
if (username == '') {
$("#username").after('<span style="color:red" class="error"><p></p>Please enter a username.</span>');
hasError = true;
} else if (passwordVal == '') {
$("#password").after('<span style="color:red" class="error"><p></p>Please enter a password.</span>');
hasError = true;
} else if (check_password() != 73) {
hasError = true;
$("#password").after(check_password());
}
if (hasError == true) {
return false;
}
});
});
For some reason the if statement is returning true even when the index(return value) is 73. I test this by using jquery within the if statement to print out the value of the returning function and it prints out 73. I have a feeling my error is caused because of dynamically typed variables in javascript.
Typical asynchronous behavior issue of AJAX calls. You return response.indexOf('success'); from your AJAX callback, but since it is an asynchronous callback, there is nothing to return to. The rest of you check_password function has long finished when the callback is being called.
To fix this you need to completely restructure your code. In your click handler, you first need to call your post() function and then in the callback you need to go through your if/else if blocks.
Your function ´checkpassword()´ doesn't actually return a value.
It launches a request to a PHP-file and immediately returns (without a value).
You do specify a callback for when the call returns, but that never gets back to your original function.
You could do something like this:
function check_password(callback){
var username = $("#username").val();
if(username.length > 0){
var bool = -1;
$('#Loading2').show();
$.post("check_login.php", {
username: $('#username').val(),
password: $('#password').val(),
}, function(response){
$('#Info2').fadeOut(500);
$('#Loading2').hide();
bool = response.indexOf('success');
setTimeout("finishAjax('Info2', '"+escape(response)+"')", 450);
$('#password').after(bool);
callback(response.indexOf('success'));
});
}
}
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn(750);
}
jQuery(function(){
$("#submitl").click(function(){
$(".error").hide();
var hasError = false;
var passwordVal = $("#password").val();
var username = $("#username").val();
if (username == '') {
$("#username").after('<span style="color:red" class="error"><p></p>Please enter a username.</span>');
hasError = true;
}
else if (passwordVal == '') {
$("#password").after('<span style="color:red" class="error"><p></p>Please enter a password.</span>');
hasError = true;
}
else (
check_password(function(returnValue) {
if (returnValue != 73) {
hasError = true;
$("#password").after(check_password());
}
})){
}
if(hasError == true) {return false;}
});
});
Of course, this code just shows you how to get the value inside the other function, but you still need to handle the fact that you're other function doesn't return immediately and that for example the value of HasError is not set immediately.
Your problem is that you return from within a inner function, which will never ever work in JavaScript. Pass a callback:
function check_password(callback) {
// ...
callback(response.indexOf('success'));
}
// ...
check_password(function(result) {
if(result != 73) {
// ...
}
})
Just search for JavaScript AJAX and you will find a lot of sites to study. Here is one of them: http://www.html5rocks.com/en/tutorials/async/deferred/

Categories