I am trying to understand how AJAX works. I have a problem in my code and I think it comes from the fact that AJAX is asynchronous (It might not be reason of the problem though). I am asking for your help to figure out what is wrong.
This is my javascript function. It calls a php page that check if the email is already in the database.
function validateEmail() {
var email = $("#email").val();
var isValid = false;
if (email == "" || email.length == 0) {
$("#emailresult").html("You must enter your email");
isValid = false;
} else if (email.length > 50) {
$("#emailresult").html("Your email cannot have more than 75 characters");
isValid = false;
} else {
$.post("checkemail.php", { email: email }, function(result) {
if (result == 1) {
alert("Inside result==1");
$("#emailresult").html("Valid");
isValid = true;
alert(isValid);
} else {
alert("Inside result != 1");
$("#emailresult").html("Already in use");
isValid = false;
}
});
}
alert(isValid);
return isValid;
}
Assume that checkemail.php
returns 1. The alerts I have are:
Inside result==1
true
false
So, in the end, the value returned is always false
even if the email should be valid. Anyone can help me fix this?
Thank you!