0

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?

Ganesh Aher
  • 1,118
  • 3
  • 21
  • 51
  • Check out [this](https://stackoverflow.com/questions/9347282/using-jquery-preventing-form-from-submitting) – Swati Feb 24 '19 at 06:26
  • try timming your variable before checking as if($.trim($('#account').val()) == "") to avoid form submission with whitespace. – Rohit Mittal Feb 24 '19 at 08:23

2 Answers2

0

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();
       },
    });
  }
});
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
0

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

A.Abdelhak
  • 140
  • 4