简体   繁体   中英

bootstrap 5 form validation post with ajax

if the check is successful how can i serialize and post the data.

Standart validation javascript:

 (function () {
'use strict'

// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('#contact-form')

// Loop over them and prevent submission
Array.prototype.slice.call(forms)
  .forEach(function (form) {
    form.addEventListener('submit', function (event) {
      if (!form.checkValidity()) {
        event.preventDefault()
        event.stopPropagation()
      }

      form.classList.add('was-validated')
    }, false)
  })
})();

You can try the code as below, it worked for me:

<form class="needs-validation" role="form" id="contact-form" method="post" novalidate>
        <input type="text" name="fullname" value="">
        <input type="email" name="email" value="">
<button type="button" id="submit">Send</button>
</form>
<script type="text/javascript">
  $(document).ready(function() {

$("#submit").click(function() {
    var form = $("#contact-form")

    if (form[0].checkValidity() === false) {
      event.preventDefault()
      event.stopPropagation()
    } else {
        var data = form.serialize();
        // console.log(data);
        $.ajax({
        type : 'POST',
        url  : '/submit.php',
        data : data,
        success :  function(data)
               {
                // console.log(data);
                    if(data.succ == 1)
                    {
                        console.log('Success');
                    }else{
                        console.log('Error');
                    }
               },
        error: function (data) {
                // console.log(data);
            }
        });
    }
    form.addClass('was-validated');

  });    
});
</script>

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