I'm using formspree for a one-field form on my page. To avoid redirecting my users to the default thank you page, I'm trying to use ajax to submit the form and display success/error messages.
However, my code isn't working. As far as I can tell, the messages don't appear. I think it has something to do with the messages wanting to display within my button, and my button being an input field..
Here's the fiddle, and here's the code:
HTML:
<div id="contactFormWrapper">
<form id="contact-form" action="http://formspree.io/myemail@gmail.com" method="POST">
<input type="message" name="name" value placeholder="Chanel Boy.." class="design--form">
<input id="send-button" type="submit" class="btn--main" style="width:auto" value="SUBMIT">
</form></div>
JS:
var contactForm = document.querySelector('#contact-form'),
inputName = contactForm.querySelector('[name="name"]'),
sendButton = contactForm.querySelector('#send-button');
sendButton.addEventListener('click', function(event){
event.preventDefault(); // prevent the form to do the post.
sendButton.innerHTML = 'Sending..';
var xhr = new XMLHttpRequest();
xhr.open('POST', '//formspree.io/myemail@gmail.com', true);
xhr.setRequestHeader("Accept", "application/json")
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.send(
"name=" + inputName.value;
xhr.onloadend = function (res) {
if (res.target.status === 200){
sendButton.innerHTML = 'Message sent!';
}
else {
sendButton.innerHTML = 'Error!';
}
}
});
Thanks!