将ajax提交添加到页面后,表单验证退出工作

时间:2019-04-02 19:58:53

标签: javascript jquery ajax

我有一个常规的表单提交页面,该页面采用了旧的时尚方式,可以很好地使用表单验证javascript。见下文。我将页面更改为通过ajax提交,现在跳过了表单验证。我如何“结合”两者以使其全部起作用?我认为我需要以某种方式将验证移至ajax帖子中,但我无法弄清楚。任何帮助将不胜感激。

<form class="card"  name="myform" id="myform">
          <div class="card-body">
                <h3 class="card-title">Add New Blog Post</h3>
                <div id='response'></div>
              <div class="row">
                <div class="col-md-4">
                  <div class="form-group">
                    <label class="form-label">Blog Title</label>
                    <input name="subject" type="text" required class="form-control" id="subject" required>
                        <div class="is-valid"></div>
                  </div>
                </div>
          </div>
</form>
<script>
     (function() {
 'use strict';
 window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles 
//to
   var forms = document.getElementsByClassName('card');
   // Loop over them and prevent submission
   var validation = Array.prototype.filter.call(forms, function(form) {
     form.addEventListener('submit', function(event) {
       if (form.checkValidity() === false) {
         event.preventDefault();
         event.stopPropagation();
       }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
 </script>

 <script>
    $(document).on("click","#submitbtn",function(e){  
       //Prevent Instant Click  
        e.preventDefault();
      $(document).ajaxSend(function(event, request, settings) {
         $('#loading-indicator').show();
           $("#submitbtn").prop('disabled', true);
           });

        $(document).ajaxComplete(function(event, request, settings) {
         $('#loading-indicator').hide();
         $("#output").fadeTo(4000, 500).slideUp(500, function(){
         $("#output").slideUp(500);
         });
           $("#myform")[0].reset();
           $("#submitbtn").prop('disabled', false);
          });

           var formData = new FormData($('#myform')[0]);    
         $.ajax({
             url: 'add_blog_do.php',
             enctype: 'multipart/form-data',
             type: 'POST',
             data: formData,
             success: function(response) {console.log(response);},
             contentType: false,
             processData: false,
             cache: false

                    });
             });

           </script>

1 个答案:

答案 0 :(得分:2)

您已经将AJAX调用附加到了“提交”按钮上的click事件中。这会在提交事件之前 触发。由于您在“提交”按钮单击处理程序中调用event.preventDefault(),因此submit事件永远不会运行。

您将需要在submit事件处理程序中触发AJAX调用,或者将其移至click处理程序中。表单通过有效性检查后,您可以触发实际的AJAX调用。

一个例子:

<form class="card"  name="myform" id="myform">
          <div class="card-body">
                <h3 class="card-title">Add New Blog Post</h3>
                <div id='response'></div>
              <div class="row">
                <div class="col-md-4">
                  <div class="form-group">
                    <label class="form-label">Blog Title</label>
                    <input name="subject" type="text" required class="form-control" id="subject" required>
                        <div class="is-valid"></div>
                  </div>
                </div>
          </div>
</form>
<script>
    $(document).on("click","#submitbtn",function(e){  
       //Prevent Instant Click  
      e.preventDefault();

      // Fetch all the forms we want to apply custom Bootstrap validation styles to
      var forms = document.getElementsByClassName('card');
      // Loop over them and prevent submission
      var validation = Array.prototype.filter.call(forms, function(form) {
        form.addEventListener('submit', function(event) {

          // Check and see if the form is INVALID
          // if it is, it currently console logs.
          // You may want to do something else here but that's up to you
          if (form.checkValidity() === false) {
              console.log('Form validation failed')
          } else {

            // If the form DOESN'T fail, we'll enter this block and run our AJAX 
            // call as normal
            form.classList.add('was-validated');
            var formData = new FormData($('#myform')[0]);    
            $.ajax({
              url: 'add_blog_do.php',
              enctype: 'multipart/form-data',
              type: 'POST',
              data: formData,
              success: function(response) { console.log(response); },
              contentType: false,
              processData: false,
              cache: false
            });
          }
    });
  }, false);

    // AJAX Event Listeners for ajaxSend and ajaxComplete
    $(document).ajaxSend(function(event, request, settings) {
        $('#loading-indicator').show();
          $("#submitbtn").prop('disabled', true);
          });

      $(document).ajaxComplete(function(event, request, settings) {
        $('#loading-indicator').hide();
        $("#output").fadeTo(4000, 500).slideUp(500, function(){
        $("#output").slideUp(500);
        });
          $("#myform")[0].reset();
          $("#submitbtn").prop('disabled', false);
        });
      });
</script>