[英]how to submit form with ajax after remote validation with jquery validation plugin
I have a form that I used jquery remote to check existing data, It check successfully, but after completing to fill the form I need to save data to the database.我有一个表格,我使用 jquery 远程检查现有数据,它检查成功,但完成填写表格后,我需要将数据保存到数据库中。 But submitHandler seems to not working.
但是 submitHandler 似乎不起作用。 Here is my sample code
这是我的示例代码
// html form // html 表格
<form action="save.php" method="post" id="createForm">
<div class="input-field">
<label for="name">Name</label>
<input type="text" name="name" id="name">
</div>
<div class="input-field">
<label for="name">Email</label>
<input type="text" name="email" id="email">
</div>
<button>save</button>
</form>
// jquery validation // jquery 验证
$('#createForm').validate({
onkeyup: false,
rules: {
name: { required: true },
email: {
required: true,
remote: {
url: 'check_email.php',
type: 'post',
dataType:'json',
dataFilter: function(data){let obj = eval('('+data+')'); return obj.valid; },
data:{email: function(){ return $('#email').val(); } }
}
}
},
messages: {
name: { required: "Enter a name." }
email: { required: "Enter a email.", remote: "{0} This email exists." }
},
submitHandler: function(form)
{
$.ajax({
url : $(form).attr('action'),
method: 'post',
data: $(form).serialize(),
dataType: 'json',
success: function(data){
show_data();
}
});
}
});
I found a solution, When using csrf token to auto generate, jquery remote validation its we can use ajaxSetup({async: false}) before jquery validation plugin initialized, or we can set remote:{ async: false }, and avoid using contentType:false by removing it.我找到了一个解决方案,当使用 csrf 令牌自动生成时,jquery 远程验证我们可以在 jquery 验证插件初始化之前使用 ajaxSetup({async: false}),或者我们可以设置远程:{ async: false },并避免使用内容:false 通过删除它。 This will prevent double request caused by remote url that ingones form action url.
这将防止由远程 url 导致的双重请求,该 ingones 形成动作 url。
ajaxSetup({
async: false
});
or或者
rules: {
email: {
required: true,
remote: {
url: 'your url',
type: 'post',
async:false,
dataType:'json',
dataFilter: function(data){let obj = eval('('+data+')'); return obj.valid; },
data:{}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.