Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Ryan Atkins
Ryan Atkins
8,635 Points

Posting with AJAX, getting 400 error

So I'm using a service called Formspree to handle my form data because I can't do the backend at this time. The problem is, I am wanting to post the data without the page changing and adding minor changes to my form's panel div to let the user know the message has been sent. In my text editor's live preview, the post works great. I get an email and the message for the user appears. However, when I bring it over to my live site, it gives me a 400 error and nothing happens. Any ideas?

$("#my-form").submit(function(evt) {
    evt.preventDefault();

    var userName = $("#name").text();
    var userSubject = $("#subject").text();
    var userEmail = $("#email").text();
    var userMessage = $("#message").text();

    $.ajax({
        url: "//formspree.io/contact@ryancatkins.com",
        method: "POST",
        data: {
            name: userName,
            subject: userSubject,
            email: userEmail,
            message: userMessage
        },
        dataType: "json"
    }).done(function () {
        $("#my-form").css("display", "none");
        $("#form-panel").append("<br><br><p class='text'>Your message has been sent.</p><br><p class='text'>Thank you!</p>");
    });
});
<div id="form-panel">
  <a href="#"><img src="assets/images/icons/formX.png" alt="contact form exit"></a>
  <form action="//formspree.io/contact@ryancatkins.com" method="post" id="my-form">
    <span>Name:</span><input  id="name" name="name" type="text"><br>
    <span>Subject:</span><input id="subject" type="text" name="_subject"><br>
    <span>E-mail:</span><input id="email" placeholder=" name@email.com" type="email" name="_replyto"><br>
    <textarea id="message" name="message" form="my-form"></textarea><br>
    <button type="submit">Send</button>
  </form>
</div>

You might want to test it in codepen.io just to confirm that the issue isn't converting between local and live. If it works in codepen then it has to be some setting on your site. Sorry I can't be of more help.