Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

297
Views
how to post data using AJAX with validation using bootstrap 5?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!