jQuery AJAX throws error even when it returns true
I am checking out AJAX inside a addMethod of jquery.validate plugin. Even w开发者_运维技巧hen the AJAX call returns true, an Error is displayed.
This is the code:
$.validator.addMethod("checkMail", function(value, element) {
var email_id = value;
$.ajax({
type: "POST",
url: "ajax_validation.php",
data: {'category_email_mode' : 'add_email', 'email' : email_id},
dataType: "text",
success: function(msg){
if(msg == 'true')
{
return true;
}
else(msg == 'false')
{
return false;
}
}
});
}
},"Email id is already choosen");
When ajax return true, true is not returned by the function. What's wrong?
AJAX doesn't work that way. You can't return a value from a success callback -- the callback is simply what's run on the data after the AJAX request is successful.
If you must use AJAX to do this, you need to make it synchronous:
$.validator.addMethod("checkMail", function(value, element) {
var email_id = value;
var valid = false;
$.ajax({
async: false, // make it synchronous
type: "POST",
url: "ajax_validation.php",
data: {'category_email_mode' : 'add_email', 'email' : email_id},
dataType: "text",
success: function(msg){
valid = (msg=='true');
}
});
return valid;
}
},"Email id is already choosen");
That said, you're probably better off using inline PHP instead of an AJAX call to do the validation.
精彩评论