Initial public commit
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
//=require element-closest/closest.js
|
||||
//=require whatwg-fetch/fetch.js
|
||||
|
||||
(function(app) {
|
||||
'use strict';
|
||||
|
||||
// Listen on submit events on body (events from forms will bubble up)
|
||||
document.body.addEventListener('submit', function(e) {
|
||||
// Find closest form parent
|
||||
var form = e.target.closest('.contact__form');
|
||||
|
||||
// Only continue if the form was found and if we have Promise support
|
||||
if(!form || !Promise) return;
|
||||
e.preventDefault();
|
||||
|
||||
// Disable the submit button and display the animated stamp
|
||||
console.info('Sending form data');
|
||||
form._submit.disabled = true;
|
||||
form.classList.add('form--sent');
|
||||
|
||||
// Get form data
|
||||
// Explicitly add value of submit button (browser bug in Chrome/FF?)
|
||||
var data = new FormData(form);
|
||||
data.append('_submit', form._submit.value);
|
||||
|
||||
// Send the form data via AJAX
|
||||
var options = {
|
||||
method: 'POST',
|
||||
body: data,
|
||||
credentials: 'same-origin',
|
||||
headers: {'Accept': 'application/json'}
|
||||
};
|
||||
var dataPromise = fetch(form.action, options)
|
||||
.then(app.validateHttpStatus)
|
||||
.then(app.parseJsonResponse);
|
||||
|
||||
// Wait for the stamp animation
|
||||
Promise.all([dataPromise, app.timerPromise(750)])
|
||||
.then(function(values) {
|
||||
// Get the result of the data promise
|
||||
var data = values[0];
|
||||
|
||||
// Mark the (in)valid fields
|
||||
for(var field in data.fields) {
|
||||
// Add the class if value is true, otherwise remove it
|
||||
form[field].classList.toggle('input--invalid', data.fields[field]);
|
||||
}
|
||||
|
||||
// Check if the form submission was successful
|
||||
if(data.success) {
|
||||
form.querySelector('.form__message').innerText = '';
|
||||
document.querySelector('.contact__thank-you').innerText = data.message;
|
||||
form.classList.add('form--success');
|
||||
} else {
|
||||
// Throw message to catch it below, because apparently our code is a dog
|
||||
throw data.message;
|
||||
}
|
||||
})
|
||||
.catch(function(err) {
|
||||
console.error(err);
|
||||
|
||||
// Display the error to the user
|
||||
form.classList.remove('form--sent');
|
||||
form.querySelector('.form__message').innerText = err;
|
||||
|
||||
// Enable the submit button again
|
||||
form._submit.disabled = false;
|
||||
});
|
||||
});
|
||||
})(window.app = window.app || {});
|
||||
Reference in New Issue
Block a user