tinyforms/app/javascript/tinyforms.js
Michael Bumann e46e68cc22 Add demo page
The demo page shows a form and an embedded google sheet side by side.
The form needs be be configured with a DEMO_FORM_ID environment variable.
2020-04-12 01:01:28 +02:00

52 lines
1.4 KiB
JavaScript

window.tinyforms = {
init: function() {
var forms = document.querySelectorAll('form[data-tinyforms]');
forms.forEach(function(form) {
form.addEventListener('submit', tinyforms.onSubmit);
});
},
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();
return tinyforms.submitForm(this)
.then((response) => {
this.dispatchEvent(new CustomEvent('tinyforms:submitted', {detail: { response: response }}));
})
.catch((response) => {
this.dispatchEvent(new CustomEvent('tinyforms:error', {detail: { response: response }}));
});
}
};
document.addEventListener('DOMContentLoaded', function() {
tinyforms.init();
});