1

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?

7
  • Any example how you post a form with data? Commented Dec 29, 2021 at 12:27
  • its doesn't matter for me. validation is working good. but I don't know; how can I add Ajax POST with bootstrap 5 standart validation Commented Dec 29, 2021 at 12:31
  • Why do you use event.preventDefault()? If you just want to post when the form is submitted, you can just remove it. Commented Dec 29, 2021 at 12:33
  • I want it to check and send. Commented Dec 29, 2021 at 12:35
  • The form would be checked when you submit it. You don't need to explicitly to use form.checkValidity(). Commented Dec 29, 2021 at 12:37

2 Answers 2

3

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)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0
(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()
                } else {
                    event.preventDefault();  // event.default or form submit
                    formPost();  // call function whatever you want
                }
                form.classList.add('was-validated')
            }, false)
        })
})()

function formPost(){
    var form_data = $("form#mainform").serialize();

    $.ajax({
        url: "action.php",
        method: "POST",
        data: form_data,
        // dataType:"json",
        success: function (data) {
            $('#queryResulDiv').html(data);
            console.log(data);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#queryResulDiv').html("ERROR:" + xhr.responseText + " - " + thrownError);
        },
        complete: function () {

        }
    })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.