Home > other >  how to post data using AJAX with validation using bootstrap 5?
how to post data using AJAX with validation using bootstrap 5?

Time:01-01

How can I post ajax with form validation in bootstrap 5 ?

 // Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
  'use strict'

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

  // 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)
    })
})()

I have a big problem with this. Can somebody help me?

CodePudding user response:

The above starter code provided by bootstrap documentation uses the checkValidity() method of JavaScript Constraint Validation API to validate the form.

The HTMLInputElement.checkValidity() method returns a boolean value which indicates validity of the value of the element. If the value is invalid, this method also fires the invalid event on the element.

You can make the ajax request if validation is successful as below,

if (!form.checkValidity()) {
   event.preventDefault()
   event.stopPropagation()
}else{
   //make your ajax request here
}

Here is an example ajax request using JavaScript Fetch API and FormData API

if (!form.checkValidity()) {
   event.preventDefault()
   event.stopPropagation()
}else{
  try {
     const postData = new FormData(form)
     const response = await fetch('url', {
         method: 'POST',
         headers: {
           'Content-Type': 'application/json'
         },
         body: JSON.stringify(postData)
      });
     //Response from server
     const data = await response.json();
  }catch(e){
     //handle error
     console.log(e)
  }
}
  • Related