I'm using xVal with MVC and jquery validate. It all works nicely, until i get to my custom validator that does an ajax call.
the ajax call returns the right value, according to the firbug Net Tab. But something is going wrong and I can't figure it out.
Here's the javascript code:
function CheckEmail() {
var res;
$.ajax({
type: "GET",
url: "/User/CheckEmail",
data: "email=" + $('#EmailAddress').val(),
success: function(result) {
res = result;
}
});
if (res == "True") {
return true;
}
else {
return false;
}
}
when i step through with firebug, res is showing as undefined. i think that's the problem.
i've spent like 4 hours re-arranging and changing this code and nothing seems to make it work properly.
I have a theory that it's not waiting until the ajax is done to run the if statement. Can anyone confirm or deny that?
There's no need for a synchronous call to your web server. You should avoid those as much as possible, because the user's browser will be locked up during while it's waiting for the reply.
I've recently written a blog article about remote client-side validation (exactly what you are trying to achieve) showing how to do this with an asynchronous request.