61 lines
1.8 KiB
JavaScript
61 lines
1.8 KiB
JavaScript
(function collonadeClosure() {
|
|
'use strict';
|
|
|
|
window.utils = window.utils || {};
|
|
|
|
var ASYNC_FORM_RESPONSE_CLASS = 'async-form-response';
|
|
var ASYNC_FORM_LOADING_CLASS = 'async-form-loading';
|
|
var ASYNC_FORM_MIN_DELAY = 600;
|
|
|
|
window.utils.asyncForm = function(formElement, options) {
|
|
|
|
var lastRequestTimestamp = 0;
|
|
|
|
function setup() {
|
|
formElement.addEventListener('submit', submitHandler);
|
|
}
|
|
|
|
function processResponse(response) {
|
|
var responseElement = document.createElement('div');
|
|
responseElement.classList.add(ASYNC_FORM_RESPONSE_CLASS);
|
|
responseElement.innerHTML = response.content;
|
|
var parentElement = formElement.parentElement;
|
|
|
|
// make sure there is a delay between click and response
|
|
var delay = Math.max(0, ASYNC_FORM_MIN_DELAY + lastRequestTimestamp - Date.now());
|
|
setTimeout(function() {
|
|
parentElement.insertBefore(responseElement, formElement);
|
|
formElement.remove();
|
|
}, delay);
|
|
}
|
|
|
|
function submitHandler(event) {
|
|
event.preventDefault();
|
|
|
|
formElement.classList.add(ASYNC_FORM_LOADING_CLASS)
|
|
lastRequestTimestamp = Date.now();
|
|
|
|
var url = formElement.getAttribute('action');
|
|
var headers = { };
|
|
var body = new FormData(formElement);
|
|
|
|
if (options && options.headers) {
|
|
Object.keys(options.headers).forEach(function(headerKey) {
|
|
headers[headerKey] = options.headers[headerKey];
|
|
});
|
|
}
|
|
|
|
window.utils.httpClient.post(url, headers, body)
|
|
.then(function(response) {
|
|
return response.json();
|
|
}).then(function(response) {
|
|
processResponse(response[0])
|
|
}).catch(function(error) {
|
|
console.error('could not fetch or process response from ' + url, { error });
|
|
});
|
|
}
|
|
|
|
setup();
|
|
};
|
|
})();
|