Javascript If statement evaluation not working correctly [duplicate] - javascript

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/

Related

JavaScript function sending string but receiving Boolean value

I am facing the unexpected behavior of javascript function. Im an passing the ID of a field as string to function but it is receiving as bool value. Please help the code is below.
Function
function page_smooth_scroll(target_id) {
if (target_id =! null) {
$j('html, body').animate({
scrollTop: $j("#" + target_id).offset().top - 120
}, 500);
}
}
calling function
function validatePassword(){
var validPassword = false;
var pwd = $j("#Password").val().trim();
var cfmPwd = $j("#ConfirmPassword").val().trim();
if((pwd == "") || (cfmPwd == "")){
$j("#ConfirmPassword").addClass("invalidPwd").nextAll("ul.err-msg").html("<li>Please enter Password</li>");
//here id is passed as string
page_smooth_scroll("ConfirmPassword");
validPassword = false;
}
else{
$j("#ConfirmPassword").removeClass("invalidPwd").nextAll("ul.err-msg").empty();
if(pwd != cfmPwd){
$j("#ConfirmPassword").addClass("invalidPwd").nextAll("ul.err-msg").html("<li>Password does not match</li>");
//here id is passed as string
page_smooth_scroll("ConfirmPassword");
validPassword = false;
}
else{
$j("#ConfirmPassword").removeClass("invalidPwd").nextAll("ul.err-msg").empty();
validPassword = true;
}
}
return validPassword;
}
the image is below while debugging
passing string
receiving bool
if (target_id =! null) {
I think you mean a != b
Because a=!b means a = !b which means "assign the opposite boolean value", which will indeed turn anything into a boolean.
Next time if you think a function is "receiving a boolean", make sure to debug the value before running any statements. I'm sure it's still a string when going into the function.

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

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

jquery function doesn't return values correctly

I have this function
$.fn.validate.checkValidationName = function(id) {
$.post("PHP/submitButtonName.php", {checkValidation: id},
function(data) {
if(data.returnValue === true) {
name = true;
} else {
name = false;
}
**console.log("name = "+name); **//this prints out "true"****
}, "json");
};
and this .click function that calls it. All the variables are declared outside this function so that they should be accessible by other functions
$('.submitBtn').click(function() {
//clears the array before re-submitting the click function
nameValues = [];
usernameValues = [];
emailValues = [];
name = false;
username = false;
email = false;
//for each of the input tags
$("input").each(function() {
//if the curent input tag has the class .name, .userpass, or .email
if(($(this).hasClass("name"))) {
nameValues.push($(this).val());
} else if(($(this).hasClass("userpass"))) {
usernameValues.push($(this).val());
} else if(($(this).hasClass("email"))) {
emailValues.push($(this).val());
}
});
//call the checkValidation function with the array "values"
$.fn.validate.checkValidationName(nameValues);
$.fn.validate.checkValidationUsername(usernameValues);
$.fn.validate.checkValidationEmail(emailValues);
console.log("name = "+name); //but this prints out "false"
console.log("username = "+username);
console.log("email = "+email);
if((name === "true") && (username === "true") && (email === "true")) {
alert("Everything checks out great");
} else {
alert("You missed one!");
}
});
When I click the link to trigger the first function, it returns the value as "true" inside the function, but when I console.log("name"+name); in the .click function after the function call, it prints out false.
Why is this? Do I need to return something from the checkValidatoinName function?
$.post is asynchronous, which means that it won't wait for the result to get back before proceeding. You're probably initializing name to true somewhere, and it's getting true the first time, but all the other times, it's false, because the AJAX from the first one finished and set it to false.
Try using $.ajax instead of $.post, and set async to false in the options. The $.post documentation shows the options that $.post would give to $.ajax.

Categories