Created
March 30, 2016 02:46
-
-
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/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@siamkreative I made the changes but when I submit it gives me undefined, here is the code https://codepen.io/eissapk/pen/qeJVxe