Skip to content

Instantly share code, notes, and snippets.

@MarineLB
Last active May 29, 2018 17:02
Show Gist options
  • Save MarineLB/e8f226e82803a004a10fc49745bd6d64 to your computer and use it in GitHub Desktop.
Save MarineLB/e8f226e82803a004a10fc49745bd6d64 to your computer and use it in GitHub Desktop.
Send an email via formspree with AJAX submit (inspired by https://gist.github.com/jannecederberg/785c1dc78e882b6bf85a5e77b31b0678#file-formspree-js)
// get the form element
const form = document.querySelector('form');
// execute function when form is submitted
form.addEventListener("submit", function(e) {
// prevent form submit and page refresh
e.preventDefault();
// find the submit button with class
const $submit = form.querySelector('.contact__submit');
// add the class 'clicked' to the button, to apply some nice styles
$submit.classList.add('clicked');
// start an axios request to actually send the email via formspree
axios({
// post method is required
method: 'post',
// replace [email protected] with yours, no need to sign up
url: 'https://formspree.io/[email protected]',
// see the helper function below to serialize the form fields and send it
data: serialize(form)
})
.then(function(response) {
// add 'submitted' class to update css
$submit.classList.add('submitted');
// clear all the form fields
form.reset();
// after 5 seconds, reset the button to its primary state
setTimeout(function() {
$submit.classList.remove('clicked');
$submit.classList.remove('submitted');
}, 5000);
// TODO : hide the fields or empty them
})
// if there is an error, do something
.catch(function() {
console.log('ERROR!!');
});
// this gist uses axios which is based on Promises and needs to be polyfilled in some browsers
// https://github.com/stefanpenner/es6-promise
});
// source : https://plainjs.com/javascript/ajax/serialize-form-data-into-a-query-string-45/
function serialize(form) {
var field, l, s = [];
if (typeof form == 'object' && form.nodeName == "FORM") {
var len = form.elements.length;
for (var i = 0; i < len; i++) {
field = form.elements[i];
if (field.name && !field.disabled && field.type != 'file' && field.type != 'reset' && field.type != 'submit' && field.type != 'button') {
if (field.type == 'select-multiple') {
l = form.elements[i].options.length;
for (var j = 0; j < l; j++) {
if (field.options[j].selected)
s[s.length] = encodeURIComponent(field.name) + "=" + encodeURIComponent(field.options[j].value);
}
} else if ((field.type != 'checkbox' && field.type != 'radio') || field.checked) {
s[s.length] = encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value);
}
}
}
}
return s.join('&').replace(/%20/g, '+');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment