Skip to content

Instantly share code, notes, and snippets.

@siamkreative
Created March 30, 2016 02:46
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save siamkreative/d243dd846f706a9c5e12edad19467b4b to your computer and use it in GitHub Desktop.
Save siamkreative/d243dd846f706a9c5e12edad19467b4b to your computer and use it in GitHub Desktop.
A plain JavaScript AJAX Contact Form that is designed to work with http://formspree.io/
/**
* AJAX Form
* http://stackoverflow.com/a/13038218/1414881
*/
var form = document.getElementById('contact_form');
// Append the form status
var formStatus = document.createElement('div');
formStatus.setAttribute('class', 'form-status alert');
form.appendChild(formStatus);
form.onsubmit = function (e) {
// Stop the regular form submission
e.preventDefault();
// Collect the form data while iterating over the inputs
var data = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
}
// Construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Accept', 'application/json; charset=utf-8');
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
// Send the collected data as JSON
xhr.send(JSON.stringify(data));
// Callback function
xhr.onloadend = function (response) {
if (response.target.status === 0) {
// Failed XmlHttpRequest should be considered an undefined error.
formStatus.className += ' alert-danger';
formStatus.innerHTML = form.dataset.formError;
} else if (response.target.status === 400) {
// Bad Request
formStatus.className += ' alert-danger';
formStatus.innerHTML = JSON.parse(responseText).error;
} else if (response.target.status === 200) {
// Success
formStatus.className += ' alert-success';
formStatus.innerHTML = form.dataset.formSuccess;
}
};
};
@eissapk
Copy link

eissapk commented Aug 11, 2019

awesome but what if I want it to work with MailChimp what should I do then

@siamkreative
Copy link
Author

@eissapk You need to change the form action and probably need to remove the Headers (both 'Accept' and 'Content-Type'). Lemme know if you need help

@eissapk
Copy link

eissapk commented Aug 15, 2019

@siamkreative I made the changes but when I submit it gives me undefined, here is the code https://codepen.io/eissapk/pen/qeJVxe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment