Proper way to submit netlify forms with SSR frameworks like svelte / sapper

Does this help: Form 404 - Static Form in Svelte / Sapper - #2 by jen?

Depends on you. JavaScript form submission via AJAX will allow you to submit the form data without the page getting refreshed. You then have to manipulate your DOM to show/hide success/error messages. If you are fine with the page reloading, you don’t need to.

Regarding the how part, the form docs already have a jQuery example.

Here’s a rough vanilla JS example:

/* assumed that your form will have a class named 'contact-form' */
var form = document.querySelector('.contact-form');

/* form submission handler */
form.addEventListener('submit', function(e)
  {
    e.preventDefault(); // disables the default form submit action

    /* gathers form data to submit */
    var XHR = new XMLHttpRequest();
    var FD = new FormData(form);

    /* submission successful */
    XHR.addEventListener('load', function(event)
      {
        /* show your success message */
      }

    /* submission failed */
    XHR.addEventListener('error', function(event)
      {
        /* show your error message */
      }

    /* actually submits the form */
    XHR.open('POST', '#');
    XHR.send(FD);
  }
1 Like