我正在使用 jQuery 验证并通过 ajax 处理表单,这样我就可以避免页面刷新。我遇到的问题是,我无法弄清楚将 ajax 代码放置在验证函数中的位置,以便表单在验证之前不会发送数据。
例如:
$('#ticket_purchasing').validate({ // initialize the plugin
rules: {
firstname: {
required: true
},
lastname: {
required: true
},
phone: {
required: true,
digits: true,
},
email: {
required: true,
email: true
},
address: {
required: true
},
city: {
required: true
},
state: {
required: true
}
},
invalidHandler: function (event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = "All fields in red must be filled*";
$("div.error-message span").html(message);
$("div.error-message").show();
} else {
$("div.error-message").hide();
}
},
submitHandler: function (form) { // for demo
// Do stuff here
}
});
$('form#ticket_purchasing').on('submit',function(e) {
//Send the serialized data to mailer.php.
$.ajax({
url:'ticket-purchase.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
// $('#sponsorship_request').slideUp();
// $('#ticket_purchasing').hide();
// $('.seats-form').fadeIn(1000);
},
error:function(data){
$("ticket_purchasing .error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
//$.post("mailer.php");
//Take our response, and replace whatever is in the "form2"
//div with it.
// $('#form2').show();
});
正如您在上面看到的,我将两个功能彼此分开,因此表单正在提交数据(通过电子邮件发送信息),即使它尚未经过验证。我尝试使用 form.submit();如验证器文档中所示,并将 ajax 代码放在那里,但这是一个我无法解决的错误。
建议?我可能完全错了哈哈。
编辑:刚刚添加了表单的 html:https://gist.github.com/adrianrodriguez/26b6beee8bf5ba85a8ce
需要明确的是,该表单在没有验证部分的情况下也可以正常工作,这意味着我可以在不刷新页面的情况下提交和收集数据,而无需使用验证插件。
最佳答案
删除您的 $.ajax
调用,因为实际的表单提交应该在 validate.submitHandler
中验证之后发生。
$('form#ticket_purchasing').validate({
//validation rules here
//invalid handler goes here
submitHandler: function(form) {
$.post('ticket-purchase.php', $('#ticket_purchasing').serialize(), successCallback());
}
});
顺便说一句,将您的 $.ajax
更改为 $.post
关于javascript - 验证并提交表单,无需刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22102035/