Vitali Ponomar Vitali Ponomar - 9 months ago 28
Javascript Question

jQuery ajax: how to destroy submit if ajax validation fails?

I have email field in user's settings area. All emails are unique, of course, so I need to check is email not used already by someone else before submitting the form.

Here is the code:

var email = $("input#email-id").val();

$("#form-id").submit(function(){
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data != 'ok'){
alert("Email is used already");
return false;
}
}
});
});


So, if
data
is not
'ok'
it must destroy submitting the form because
if()
returns
false
, but it doesn't and the form submits as usual and even alert doesn't appear!

I've checked ajax answer and it works fine (returns
'user_already'
if email is used).
So what I did wrong?

Thanks!

Answer Source

Since ajax is async by nature you cannot do that. If you really want to do that you can submit the form inside the success handler. Try this.

function submitHandler(){
    var email = $("input#email-id").val();

    $.ajax({
        url: "/ajax/email?email=" + email,
        success: function(data){
            if(data != 'ok'){
                alert("Email is used already");
                return false;
            }
            else{
               //Once the data is ok you can unbind the submit handler and 
               //then submit the form so that the handler is not called this time
               $("#form-id").unbind('submit').submit();
            } 
        }
    });
    return false;//This will prevent the form to submit
}
$("#form-id").submit(submitHandler);