Jquery: return: false on submit not working - form still submits

北战南征 提交于 2019-11-28 06:48:51

问题


Is there a reason that the form is still submitting? The validation checks work but if it everything is input correctly, the form submits and the ajax request does not fire.

$("#formRegister").submit(function () {
// Start problem
    var mode = $("registerMode").val();
// End problem
    var username = $("#registerUsername").val();
    var password = $("#registerPassword").val();
    var passwordConfirm = $("#registerPasswordConfirm").val();
    var avatar = $("#registerAvatar").val();

    if (username == 'Username') {
        $("#registerError").html('You must enter a username');
    } else if (password == 'Password') {
        $("#registerError").html('You must enter a password');
    } else if (password != passwordConfirm) {
        $("#registerError").html('Your passwords did not match');
    } else if (avatar == 'Avatar URL') {
        $("#registerError").html('You must enter the URL for your combine avatar');
    } else {
        $.ajax({
            type: "POST",
            url: "processUsers.php",
            data: {
                mode: mode,
                username: username,
                password: password,
                avatar: avatar
            },
            dataType: "JSON",
            success: function(data) {
                alert('success!');
            }
        });
    }

    return false;
});

回答1:


This should work

$("#formRegister").submit(function (event) {
var username = $("#registerUsername").val();
var password = $("#registerPassword").val();
var passwordConfirm = $("#registerPasswordConfirm").val();
var avatar = $("#registerAvatar").val();

if (username == 'Username') {
    $("#registerError").html('You must enter a username');
} else if (password == 'Password') {
    $("#registerError").html('You must enter a password');
} else if (password != passwordConfirm) {
    $("#registerError").html('Your passwords did not match');
} else if (avatar == 'Avatar URL') {
    $("#registerError").html('You must enter the URL for your combine avatar');
} else {
    $.ajax({
        type: "POST",
        url: "processUsers.php",
        data: {
            mode: mode,
            username: username,
            password: password,
            avatar: avatar
        },
        dataType: "JSON",
        success: function(data) {
            alert('success!');
        }
    });
}
event.preventDefault();
});


来源:https://stackoverflow.com/questions/18335408/jquery-return-false-on-submit-not-working-form-still-submits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!