views:

1914

answers:

1

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;
}

});

+6  A: 

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.

$.ajax(
    {
    type: "POST",
    async: false,              // <- note addition
    url: "/Account/EmailExist",
    data: { 'email': emailval },
    success: function(result) {

        if (result.indb) {
            isvalid = true;

        }
    },
    error: function(error) {
        alert(error);
    }
});

OR

$("input[type=submit]").click(function() {

    // email - check required and valid

    var form = $(this).parent('form');
    var email = $("input[name='email']");
    var emailtrim = jQuery.trim(email.val());

    SubmitIfNoEmailExists(form,emailtrim);

    return false;
});

function SubmitIfNoEmailExists(form,emailval) {

    // hit db
    $.ajax({
        type: "POST",
        url: "/Account/EmailExist",
        data: { 'email': emailval },
        success: function(result) {
            if (!result.indb) {
               form.submit();
            }
        },
        error: function(error) {
            alert(error);
        }
    });
}

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.

tvanfosson
It appears that this has not solved the issue for me. Is there anyway this could be related to the call being in an external JS file? I set a break point in both my JS and ActionMethod and the ActionMethd is not called until after all the rest of the JS code has been executed. Any more thoughts?
aherrick
I've added an alternative that has the ajax callback submit the form if the email doesn't already exist.
tvanfosson
Great! However here is the problem, I need to validate the email then continue on with more validation later in the script. Essentially if email does not exist it should not just submit the form. It should flip a bool where at the end of the javascript I either return true or false to submit.
aherrick
I suggest that you might want to consider using the jQuery validation plugin: http://plugins.jquery.com/project/validate. The Marketo validation example uses remote validation of an email address.
tvanfosson