我正在尝试在使用AJAX请求发送表单元素之前验证表单元素。它会检查错误,但会提交表单。
我的代码:
$('#accountFormAddEdit').on('submit', function(e){
e.preventDefault();
if($('#account').val() == "")
{
alert("Account name is required");
} else {
$.ajax({
url: '<?= base_url() ?>controller/method',
method: 'POST',
data: $('#accountFormAddEdit').serialize(),
beforeSend:function(){
$('#submit').val("Saving");
$('#accountForm').modal('hide');
},
success:function(data){
$('#accountFormAddEdit')[0].reset();
$('#accountForm').modal('hide');
},
dataType: 'JSON',
});
}
location.reload();
});
我正在使用HTML Modal
来显示表单And PHP Codeigniter
。
当我提交表单location.reload()
时不会刷新页面,为了获得结果,我使用了刷新页面。
那么如何检查空白并阻止表单数据提交并获得响应而无需刷新?
答案 0 :(得分:0)
当没有值然后返回false时,请使用以下函数:-
$('#accountFormAddEdit').on('submit', function(e){
e.preventDefault();
if($('#account').val() == ""){
alert("Account name is required");
return false;
} else {
$.ajax({
url: '<?= base_url() ?>controller/method',
method: 'POST',
dataType: 'JSON',
data: $('#accountFormAddEdit').serialize(),
beforeSend:function(){
$('#submit').val("Saving");
$('#accountForm').modal('hide');
},
success:function(data){
$('#accountFormAddEdit')[0].reset();
$('#accountForm').modal('hide');
location.reload();
},
});
}
});
答案 1 :(得分:0)
如果要检查空白,必须将location.reload();
放置在成功函数内或alert("Account name is required");
之后,以防止刷新事件