Form Submissions with AJAX

If you want more control over your FormKeep form, you may want to consider using JavaScript to submit. This may be a good idea if you are already using a JavaScript framework, you want to add validation logic, or you don’t want to redirect the user after they submit the form.

Cross Origin Requests are possible by submitting the form using Javascript.

You can submit to FormKeep using a standard AJAX request. To ensure the request does not cause a redirect, be sure to set the Accept header to application/javascript.

jQuery Example

The main thing to remember when using jQuery, is to set the Accept header to application/javascript. Also make sure to replace the “exampletoken” with your real token.

<html>
  <head>
    <meta charset="UTF-8" />
    <script src="https://unpkg.com/jquery/dist/jquery.js"></script>
  </head>
  <body>
    <form id="newsletter-signup"
          action="https://formkeep.com/f/exampletoken"
          method="POST"
          accept-charset="UTF-8">
      <input type="hidden" name="utf8" value="✓">
      <input type="email" name="email">
      <input value="Submit" type="submit">
    </form>

    <script type="text/javascript">
    $(function() {
      $('#newsletter-signup').submit(function(event) {
        event.preventDefault();

        var formElement = $(this);
        var submitButton = $('input[type=submit]', formElement);

        $.ajax({
          type: 'POST',
          url: formElement.prop('action'),
          accept: {
            javascript: 'application/javascript'
          },
          data: formElement.serialize(),
          beforeSend: function() {
            submitButton.prop('disabled', 'disabled');
          }
        }).done(function(data) {
          submitButton.prop('disabled', false);
        });
      });
    });
    </script>
  </body>
</html>


Axios Example

Axios is very similar, but setting the Accept header can trip people up, see the config setup below. Also make sure to replace the “exampletoken” with your real token.

<html>
  <head>
    <meta charset="UTF-8" />
    <script src="https://unpkg.com/axios/dist/axios.min.js" async></script>
  </head>
  <body>
    <form id="newsletter-signup"
          action="https://formkeep.com/f/exampletoken"
          method="POST"
          accept-charset="UTF-8">
      <input type="hidden" name="utf8" value="✓">
      <input type="email" name="email">
      <input value="Submit" type="submit">
    </form>

    <script type="text/javascript">
      // Function to handle form submission
      function handleSubmit(event) {
        event.preventDefault(); // Prevent default form submission behavior

        // Get the form element
        const form = document.getElementById('newsletter-signup');

        // Get the form data
        const formData = new FormData(form);

        const config = {
          headers: {
            'Accept': 'application/javascript', // Set the Accept header to JSON
          }
        };

        // Make a POST request using Axios
        axios.post(form.action, formData, config)
          .then(function (response) {
            // Handle the successful response
            console.log(response);
          })
          .catch(function (error) {
            // Handle the error
            console.error(error);
          });
      }

      // Add event listener to the form's submit event
      document.getElementById('newsletter-signup').addEventListener('submit', handleSubmit);
    </script>
  </body>
</html>


Javascript fetch Example

Javascript fetch is very similar, but setting the no-cors mode or not setting the accept-header can trip people up, see the config setup below. Also make sure to replace the “exampletoken” with your real token.

One note is to make sure NOT to include the no-cors mode, if you do we’ll still get the data on our side, but your javascript won’t be able to get a valid response back.

From the docs around fetch(): But when using fetch with mode: “no-cors”, the browser prevents you from being able to read anything from the resulting Response object or view the status, thus, response.ok is always false, and response.status is always set to 0. This is a security feature.

<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <form id="newsletter-signup"
          action="https://formkeep.com/f/exampletoken"
          method="POST"
          accept-charset="UTF-8">
      <input type="hidden" name="utf8" value="✓">
      <input type="email" name="email">
      <input value="Submit" type="submit">
    </form>

    <script type="text/javascript">
      // Function to handle form submission
      function handleSubmit(event) {
        event.preventDefault(); // Prevent default form submission behavior

        // Get the form element
        const form = document.getElementById('newsletter-signup');

        // Get the form data
        const formData = new FormData(form);

        // Make a POST request using javascript fetch() api
        fetch(form.action, {
          method: 'POST',
          body: formData,
          headers: {
            'Accept': 'application/javascript',
          },
        }).then(function (response) {
          // Handle the successful response, note we're not going to send anything back other than the ok status, if you've set the no-cors this is going to fail
          console.log(response.ok);
        })
        .catch(function (error) {
          // Handle the error
          console.error(error);
        });
      }

      // Add event listener to the form's submit event
      document.getElementById('newsletter-signup').addEventListener('submit', handleSubmit);
    </script>
  </body>
</html>