Skip to content

Instantly share code, notes, and snippets.

@isaactopo
Last active May 25, 2022 16:40
Show Gist options
  • Save isaactopo/0cb73732c85448f0c35af7a613c1635f to your computer and use it in GitHub Desktop.
Save isaactopo/0cb73732c85448f0c35af7a613c1635f to your computer and use it in GitHub Desktop.
AJAX Form Submit
(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) {
event.preventDefault()
event.stopPropagation()
form.classList.add('was-validated')
if (form.checkValidity()) {
submitFormAjax(form)
}
}, false)
})
function submitFormAjax(form) {
let xmlhttp = window.XMLHttpRequest ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("sent").classList.remove('d-none');
// alert(this.responseText); // Here is the response
} else {
document.getElementById("not-sent").classList.remove('d-none');
}
}
// get all the forms elements and their values in one step
let data = new FormData(form)
var object = {};
data.forEach((value, key) => {
if (!Reflect.has(object, key)) {
object[key] = value;
return;
}
if (!Array.isArray(object[key])) {
object[key] = [object[key]];
}
object[key].push(value);
});
var json = JSON.stringify(object);
xmlhttp.open("POST", form.action)
xmlhttp.send(json);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment