i am trying to check if an email exists in the db but the function doesn't return a value.
This is the code:
function checkemail(email)
{
var returnVal = "";
if (email.indexOf("@") != -1 && email.indexOf(".") != -1)
{
$.post( "registreren.php?email=" + email, function( response ) {
if(response == 1) { returnVal = 1; }
if(response == 2) { returnVal = 2; }
});
}
else
{
returnVal = 3;
}//email
return returnVal;
}
EDIT: email is send as a string
Can you use something simple like below
$.ajax({
url: 'registreren.php',
type: 'post',
dataType: "json",
data: {'email': email},
success: function (response) {
if (response == 1)
{
returnVal = 1;
}
else
{
returnVal = 3;
}
}
});
instead of
$.post( "registreren.php?email=" + email, function( response ) {
if(response == 1) { returnVal = 1; }
if(response == 2) { returnVal = 2; }
});
I short, You can not return values from
ajax
calls as it is asynchronous by nature, the statementreturn value
executes before
To address such cases, use callback
, a function accepted as argument and which is executed when response
is been received ( when asynchronous action is completed ).
Try this:
function checkemail(email, callback) { var returnVal = ""; if (email.indexOf("@") != -1 && email.indexOf(".") != -1) { $.post("registreren.php?email=" + email, function(response) { callback(response); }); } else { callback(3); } } checkemail('abc@xyz.com', function(val) { alert(val); }); checkemail('INVALID_EMAIL', function(val) { alert(val); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.