I have some jQuery code in an external Javascript file that is making an ajax call to an action method I have in my controller. The code in the external Javascript file is below. The action method is being called eventually, however it is not being called in time. When I set a break point in the action method, it is not being called until after the submit button click returns false. When the EmailExist function returns "isvalid", isvalid is undefined.
So its not a matter of the action method being called eventually, it just is not called for whatever reason EmailExist always returns undefined and the MVC Action method is not called until the button click is returned. Any thoughts?
Action Method:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult EmailExist(string email)
{
Account account = _generalService.GetAccountByEmail(email);
bool exist = false;
if (account != null)
exist = true;
return Json(new { indb = exist });
}
Javascript:
$(document).ready(function() {
$("input[type=submit]").click(function() {
var valid = true;
// email - check required and valid
var email = $("input[name='email']");
var emailtrim = jQuery.trim(email.val());
// email exists in db ajax request
if (EmailExist(emailtrim)) {
valid = false;
}
return valid;
})
function EmailExist(emailval) {
var isvalid;
// hit db
$.ajax(
{
type: "POST",
url: "/Account/EmailExist",
data: { 'email': emailval },
success: function(result) {
if (result.indb) {
isvalid = true;
}
},
error: function(error) {
alert(error);
}
});
return isvalid;
}
});