i am trying to return value from ajax request to a function on form submit.
The code is as below:
function validateEmail(){
if(email.val() == "")
{
$("#emailerror").html("Enter Email...");
return false;
}
else {
$.ajax({
type: "POST",
data: "email="+email.val(),
url:'emailcheck.php',
beforeSend: function(){
$("#emailerror").html("Checking Email...");
},
success: function(data){
if(data == "invalid")
{
$("#emailerror").html("Invalid Email");
return false;
}
else if(data != "0")
{
$("#emailerror").html("Email Already Exist");
return false;
}
else
{
$("#emailerror").html("OK");
return true;
}
}
});
}
}
On form submit, i am calling the function and checking the return value from ajax response:
$('#myForm').submit(function(){
if(validateEmail())
{
alert('returning true');
return true;
}
else
{
return false;
}
});
But, the code is not executed when the return value is ‘true’. The function validateEmail() return false.
Pls help me to figure out where i went wrong..
Thanks in advance.
The “A” in AJAX stands for “asynchronous”.
In the
elsebranch ofvalidateEmail, you’re launching an asynchronous request toemailcheck.php.validateEmailwill return before your PHP file responds; then youremailcheck.phpscript does respond, jQuery will call yoursuccesscallback but no one will pay attention to what it returns. The result as far as form validation is concerned, is that yourvalidateEmaillooks like this:You could try the
async:falseoption for$.ajaxor rework all your logic to be able to wait for the asynchronous request to return.Furthermore, the second branch of
validateEmaildoes not returnfalse, it doesn’t return anything at all but that’s still not a true value.