Formspree: Ajax submit not working

2019-08-07 19:38发布

问题:

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!

回答1:

There were a few typos and a misunderstanding on how input values work. Here is an updated fiddle.

The 2 main issues I saw, were:

  1. The xhr.send did not have a close parenthesis
  2. You can't change the text of an input (<input type="submit>) using innerHTML, you need to change the value: sendButton.value = 'Sending...';

This absolutely worked for me when I put my email address in instead of yours. I got the confirmation email from formspree and then was able to submit through the fiddle to myself.



回答2:

I did it using www.enformed.io, works just as formspree but has a redirect out of the box, works great. Also has a couple of interesting features like email customization.