Submitting Forms Using Javascript

Control what happens after your form is submitted

cover
Photo credit: Claudio Schwarz

If you want more control over your StaticForms form, you can use JavaScript (either VanillaJS or your framework of choice) to submit it.

Using Javascript to submit a form can be a great idea if you want to add more complex validation than can be done with standard HTML5 input constraints, or if you don't want to redirect the user away from the current page after they submit the form.

You can submit to StaticForms using a standard AJAX request. StaticForms will store the form data and send you a standard HTTP response to let you know all went well, or what went wrong. You can then do whatever you want. We'll provide an example below of replacing the form with a "thank you" message after sucessful submission, but you can get as creative as you like!

See a real-world example in action on our demo page or read on for a step-by-step guide.

A Vanilla Javascript Example

Let's start with a basic form (this is super-stripped down, in a real form you'd include formatting, a placeholder, accessibility information and more, but we're going to skip that for now):

<form id="sign-up-form">
<input type="email" id="email" name="email" required>
<button type="submit" id="subscribe-button">Subscribe</button>
</form>

Then sprinkle in some simple Javascript:

<script>
const form = document.getElementById('sign-up-form');

form.addEventListener('submit', function (e) {
e.preventDefault();

fetch('https://api.staticforms.co/Submit?form=<YOUR FORM ID>', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
body: JSON.stringify({ "email": document.getElementById("email").value })
})
.then(response => console.log(response))
.catch(error => console.log(error))
});
</script>

The critical things here are that

  • the method must be POST - this tells your StaticForms endopint that you are sending it data
  • the headers must set both Content-Type and Accept to application/json - this tells your StaticForms endopint that you are calling it using Javascript and sending it data in JSON format, and that it should also send its response in JSON format
  • the body (or content) of the call to your StaticForms endopint must be in JSON format - we're using the JSON.Stringify function to convert the field name and value to JSON format.

When your StaticForms endpoint has processed the form data you sent it, it sends a response indicating whether it was successful or not. In this example we are just logging it to the console.

In a real-world form you might display a message to the user after the form has been submitted. For example, if we change the Javascript above to this:


<script>
const form = document.getElementById('sign-up-form');
var message = document.createElement("div");

form.addEventListener('submit', function (e) {
e.preventDefault();

fetch('https://api.staticforms.co/Submit?form=<YOUR FORM ID>', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
body: JSON.stringify({ "email": document.getElementById("email").value })
})
.then(response => {
console.log(response);
if (response.status == 200) {
message.innerHTML = "<h1>Thank you for signing up!</h1><p>Keep an eye on your inbox for our next newsletter.</p>";
form.parentNode.replaceChild(message, form);
}
})
.catch(error => {
message.innerHTML = "<h1>Woah,something went wrong!</h1><p>We're aware of the problem and investigating. Please try again later.</p>";
form.parentNode.replaceChild(message, form);
})
});
</script>

...the form will be replaced with a new message to the user after it has been submitted.

See a real-world example in action on our demo page