60 lines
1.7 KiB
JavaScript
60 lines
1.7 KiB
JavaScript
window.tinyforms = {
|
|
init: function() {
|
|
if (tinyforms.loaded) {
|
|
return;
|
|
}
|
|
var forms = document.querySelectorAll('form[data-tinyforms]');
|
|
forms.forEach(function(form) {
|
|
form.addEventListener('submit', tinyforms.onSubmit);
|
|
});
|
|
tinyforms.loaded = true;
|
|
},
|
|
|
|
submitForm: function(form) {
|
|
return new Promise(function(resolve, reject) {
|
|
var action = form.getAttribute('action');
|
|
var formData = new FormData(form);
|
|
|
|
var xhr = new XMLHttpRequest();
|
|
xhr.open('POST', action, true);
|
|
xhr.setRequestHeader("Accept", "application/json");
|
|
xhr.onload = function () {
|
|
var response;
|
|
try {
|
|
response = JSON.parse(xhr.responseText);
|
|
} catch (e) {
|
|
response = xhr.responseText;
|
|
}
|
|
if (xhr.status >= 200 && xhr.status < 300) {
|
|
resolve(response);
|
|
} else {
|
|
reject(response);
|
|
}
|
|
};
|
|
xhr.onerror = function() {
|
|
reject(xhr.responseText)
|
|
};
|
|
xhr.send(formData);
|
|
});
|
|
},
|
|
|
|
onSubmit: function(e) {
|
|
e.preventDefault();
|
|
var form = this;
|
|
return tinyforms.submitForm(form)
|
|
.then((response) => {
|
|
this.dispatchEvent(new CustomEvent('tinyforms:submitted', {detail: { submission: response.submission, response: response }}));
|
|
if (form.dataset.tinyformsSubmitted && typeof window[form.dataset.tinyformsSubmitted] === 'function') {
|
|
window[form.dataset.tinyformsSubmitted](response.submission);
|
|
}
|
|
})
|
|
.catch((response) => {
|
|
this.dispatchEvent(new CustomEvent('tinyforms:error', {detail: { submission: response.submission, response: response }}));
|
|
});
|
|
}
|
|
};
|
|
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
tinyforms.init();
|
|
});
|