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; }
});
It looks like you want the request to be synchronous. To get this to happen you need to set the async option on the request to false. The default is to have the request be asynchronous so that you return from the ajax call before the request is complete. Alternatively, you can rewrite the code so that the success callback actually does the work. The latter is more idiomatic for AJAX — but can sometimes be more complex.
OR
EDIT: Based on your comments, you may want to also look at using the jQuery validation plugin as a solution to all of your validation needs.