简体   繁体   English

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

[英]Form validation quit working after adding ajax submission to page

I had a regular form submission page the old fashion way that used form validation javascript that worked fine. 我有一个常规的表单提交页面,它使用了可以正常工作的表单验证javascript的旧方式。 See below. 见下文。 I changed the page to submit via ajax and now the form validation is skipped. 我将页面更改为通过ajax提交,现在跳过了表单验证。 How do I "combine" the two to make it all work? 我如何“结合”两者以使其全部起作用? I assume I need to move the validation in the ajax post somehow, but I can't figure it out. 我认为我需要以某种方式将验证移至ajax帖子中,但我无法弄清楚。 Any help would be appreciated. 任何帮助,将不胜感激。

<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>

You've attached your AJAX call to the click event on your submit button. 您已经将AJAX呼叫附加到了“提交”按钮上的click事件上。 This fires before the submit event. 在提交事件之前触发。 Since you're invoking event.preventDefault() inside the submit button click handler, the submit event is never running. 由于您是在“提交”按钮单击处理程序中调用event.preventDefault() ,因此submit事件永远不会运行。

You'll want to instead fire your AJAX call in your submit event handler or move it into the click handler. 您将需要在submit事件处理程序中触发AJAX调用, 将其移至click处理程序中。 Once the form passes the validity check, you can fire off your actual AJAX call. 表单通过有效性检查后,您可以触发实际的AJAX调用。

An example: 一个例子:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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