Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

jquery - How to wait for ajax validation to complete before submitting a form?

Having a problem where the form submits before the validateUsername function has a chance to complete the username check on the server-side.

How do I submit the form only after the validateUsername function completes? Hope this is clear...

form.submit(function(){
    if (validateUsername() & validateEmail() & validatePassword()) {
        return true;
    } else {
        return false;
    }
});         

function validateUsername(){            
    usernameInfo.addClass("sign_up_drill");
    usernameInfo.text("checking...");
    var b = username.val();
    var filter = /^[a-zA-Z0-9_]+$/;     
    $.post("../username_check.php",{su_username:username.val()},function(data) {
        if (data=='yes') {
            username.addClass("error");
            usernameInfo.text("sorry, that one's taken");
            usernameInfo.addClass("error");
            return false;           
        } else if (!filter.test(b)) {
            username.addClass("error");
            usernameInfo.text("no funny characters please");
            usernameInfo.addClass("error");
            return false;   
        } else {
            username.removeClass("error");
            usernameInfo.text("ok");
            usernameInfo.removeClass("error");      
            return true;    
        }
    });             
}   
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

More verbose version of Olafur's answer - The AJAX call is made and the function returns without waiting.

The callback doesn't finish until you've submitted the form.

What you should do is have the button/trigger calling the AJAX validation, and the callback should submit the form instead of returning true.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...