首页 > 解决方案 > 如何在使用 AJAX 发送表单元素之前验证空白的表单元素?

问题描述

我正在尝试在使用 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();
      });

我正在使用 aHTML Modal来显示表单 And PHP Codeigniter

当我提交表单location.reload()时不会刷新页面,为了获得结果,我使用刷新页面。

那么如何检查空白并防止表单数据提交并在不刷新的情况下获得响应?

标签: javascriptphpjqueryajaxcodeigniter-3

解决方案


如果没有值则返回 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();
       },
    });
  }
});

推荐阅读