在jQuery表单验证后不发送POST

时间:2015-10-04 18:33:51

标签: jquery ajax forms modal-dialog

我的表单在Bootstrap模式中定义,看起来像:

<form class="contact" name="contact" id="contact-form">
    <label class="modalLabel" for="name">Name</label><br>
    <input type="text" name="name" class="input-xlarge" minlength="2" required><br>
    <label class="modalLabell" for="email">E-mail Adresse</label><br>
    <input type="email" name="email" class="input-xlarge" required><br>
    <label class="modalLabel" for="message">Any message?</label><br>
    <textarea name="message" class="input-xlarge"></textarea>
    <div>
    <input class="btn btn-success" type="submit" value="Absenden" id="submit">
    <a href="#" class="btn btn-warning" data-dismiss="modal">Doch nicht</a>
    </div>
</form>

用于AJAX和验证的jQuery:

$("#contact-form").validate({
        submitHandler: function(form) {
            $(form.contact).ajax({
                        type: "POST",
                        url: "process.php", //process to mail
                        data: $('form.contact').serialize(),
                        success: function(msg){
                            $("#thanks").html(msg) //hide button and show thank you
                            $("#form-content").modal('hide'); //hide popup  
                        },
                        error: function(){
                            alert("Bitte versuchen Sie es nochmal.");
                        }
            });
        }
});

通过将$.ajax调用放在click()函数中,我在没有验证的情况下运行了AJAX。在我使用jQuery插件添加验证后,POST不再起作用了。看起来GET现在已经完成了,我不知道如何让它发挥作用。

2 个答案:

答案 0 :(得分:1)

$(form.contact).ajax({...可能会抛出错误,因为没有选择器特定的ajax方法,并且没有对象form.contact。对于类选择器,它需要form.contact

附近的引号

尝试更改为

$.ajax({...

答案 1 :(得分:1)

请查看工作示例:http://codepen.io/anon/pen/ZbewGp

$("#contact-form").validate({
    submitHandler: function(form) {
        $.ajax({
                    type: "POST",
                    url: "process.php", //process to mail
                    data: $('form.contact').serialize(),
                    success: function(msg){
                        $("#thanks").html(msg) //hide button and show thank you
                        $("#form-content").modal('hide'); //hide popup  
                    },
                    error: function(){
                        alert("Bitte versuchen Sie es nochmal.");
                    }
        });
    }

});