简体   繁体   中英

How to validate form elements for white space before sending it using AJAX?

I'm trying to validate form elements before sending it using AJAX request. It checks for error, but form gets submitted.

My code:

$('#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();
      });

I'm using a HTML Modal to show form And PHP Codeigniter .

When I submit the form location.reload() won't refresh the page, to get the result back I use to refresh the page.

So how to check for white space and prevent the form data submission and get the response without refresh?

when there are no values then return false, use the following function:-

 $('#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();
       },
    });
  }
});

you have to place location.reload(); inside the success function or after alert("Account name is required"); to prevent refresh event if you check for the white space

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM