Posted on June 24, 2015
Here were my requirements:
It turns out that it’s really easy to get data from visitors on a static site, thanks to at least a few providers:
It’s impressively easy to get a basic form up and running. Here’s the demo straight from the Formspree homepage:
What’s really cool is that Firefox and Chrome will validate these forms based on their type, and you can type “required” (without the quotes) in the input fields for those browsers to require the data as well. Unfortunately, not all users will be on the same browsers so you can’t count on this validation. By default, when a user submits this form Formspree redirects them to a thank you page, but it’s easy to override that by including a hidden input field named _next:
So, my first requirement is met, and my second requirement is halfway met, thanks to built-in browser validation. Still, some users are going to be confused when I redirect them back to the same form page, and I don’t want to interrupt the flow by sending them to some “thanks for submitting” page. More important for now, I need to make sure validation works on all browsers.
Validation turns out to be easy, too, thanks to the jQuery Validation extension. Grab the extension and call it after calling jQuery,or just use a CDN like I did:
Like the built-in validation on Chrome and Firefox, jQuery Validation picks up on field types and the ‘required’ tab, and flags those errors. Below are the final inputs and validations for my form (with some Bootstrap-specific formatting removed:)
Of course, my form isn’t going anywhere, but the validation works, so I’m two for three on requirements. Onward to submitting the actual data without resetting the page!
The validate function can be built with several options, including a
While our form now sends, the page doesn’t change, so our users aren’t going to think the form works at all. Let’s fix that.
First, we’ll add a couple of divs to our page which are hidden by default, that will show appropriate messages after the form has been submitted: (Mine use Bootstrap’s alert components, but I’ve stripped that formatting in the interest of brevity.)
Next, we’ll add success and error handlers to our Ajax request. If I succeed, I’ll fade out the form and fade in the success message. If the request fails, I’ll display an error.
So, that’s it. Formspree is a great tool, validation is easy with plugins, and sending AJAX requests means I can have a user submit the form without sending them to a new page. Great! Want to see it in action? Check out my Contact form, and feel free to send me a note.