Skip to main content

Submitting Forms Using AJAX

If you want complete control over what happens once the user submits a form, or you need advanced validation, then submitting the form using AJAX is a good option. StaticForms form endpoints accept standard AJAX requests and work cross-origin by default.

You don't need to make any changes to your form to submit it using AJAX and you don't need any libraries or frameworks - plain, vanilla Javascript will get the job done.

A Simple Example#

Let's create a super-basic form. This one is stripped to basic - in the real-world you'd obviously add classes to style it, ensure that is accessible, etc. but we're not going to worry about that for now.

<div id="form-container">  <form id="sign-up-form" type="submit" action="POST">      <label for="email">Enter your email address</label>      <input type="email" name="email" id="email" required>      <button type="submit">Submit</button>  </form></div>

Then we just need a dash of Javascript. Paste the example code below into your web page - it can go anywhere before the </body> tag.

const form = document.getElementById('sign-up-form');const formContainer = document.getElementById('form-container');
form.addEventListener('submit', function (e) {    e.preventDefault();
    fetch('', {        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) {            var message = document.createElement("div");            message.innerHTML = "<div'><h2>Thank you for signing up!</h2></div>";            formContainer.parentNode.replaceChild(message, formContainer);        } else {            message.innerHTML = "<div><h2>Oops. Something went wrong!</h2></div>";            formContainer.parentNode.replaceChild(message, formContainer);        }    })    .catch(error => {        message.innerHTML = "<div><h2>Oops. Something went wrong!</h2></div>";        formContainer.parentNode.replaceChild(message, formContainer);    })});

This adds an event listener to the Submit button. When the button is clicked, this gets the value of the input field, packages it in to a JSON object and uses the standard JavaScript fetch method to send it to the StaticForms end-point. It then checks the response it gets back from the StaticForms end-point and swaps out the form for a message to tell the user whether or not the form was submitted successfully.

This is a super simple example, but building on this basic structure you could add validation to the form before submitting, display a sequence for forms to progressively collect data based on previous input, and much more - your imagination really is the only limit!

Check out our demo site for a fully working, and slightly more advanced, example - and feel free to steal and adapt the code for use on your own site!