Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mkamrani/7ac7906393bab567cbf780aad19b59f9 to your computer and use it in GitHub Desktop.
Save mkamrani/7ac7906393bab567cbf780aad19b59f9 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 requestDemoForm = document.getElementById('aaa_form');
var subscribeNewsLetterForm = document.getElementById('bbb_form');
// Append the form status (you can just alert instead of these)
var formStatus = document.createElement('div');
formStatus.setAttribute('class', 'form-status alert');
form.appendChild(formStatus);
requestDemoForm.onsubmit = submitForm;
subscribeNewsLetterForm.onsubmit = submitForm;
function submitForm (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;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment