Make tinyforms.js available under /tinyforms.js
This commit is contained in:
parent
23184f3266
commit
6a2db73570
59
public/tinyforms.js
Normal file
59
public/tinyforms.js
Normal file
@ -0,0 +1,59 @@
|
||||
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();
|
||||
});
|
Loading…
x
Reference in New Issue
Block a user