The devil in the details: here’s a working solution for a svelte-kit form on Netlify:
/src/routes/hello.svelte
<script context="module">
export const prerender = true;
</script>
<script>
const handleSubmit = (e) => {
e.preventDefault()
let myForm = document.getElementById('myform');
let formData = new FormData(myForm);
fetch('/', {
method: 'POST',
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(formData).toString()
}).then(() => console.log('Form successfully submitted')).catch((error) =>
alert(error))
}
</script>
<form id="myform" on:submit{handleSubmit} name="hello" method="POST" data-netlify="true">
<p><label>Your Name: <input type="text" name="name" /></label></p>
<p><label>Your Email: <input type="email" name="email" /></label></p>
<p><label>Message: <textarea name="message"></textarea></label></p>
<p><button class="mx-2 bg-red-50 border-2 px-2 rounded-md block mx-auto" type="submit">Send</button></p>
<br>
<input type="hidden" name="form-name" value="hello">
</form>
export const prerender = true;
is required to insure that an HTML form is rendered a build time, so that Netlify can register it. That directive needs to be in context=module
tagged script so that it is part of the build, not just runtime, like the submit hander is.
The body attribute of the my submit handler from the start of this thread was wrong, the working version is simply. body: new URLSearchParams(formData).toString()
The HTML form definition from the start of this thread, the name
attribute in the hidden input element was wrong in
<input type="hidden" name="contact" value="contact" />
should be
<input type="hidden" name="form-name" value="contact" />
For the sake of clarity, configuring pre-render in sevelte.config.js
that I mentioned in the thread above is not necessary for our purposes here of simply getting a form to pre-render.
In the end it’s not so complicated, but there are so many fragments of examples, that its easy to miss details. It’s nice to see form posts working now in Svelte-kit and Netlify!