I recently moved my website to a svelte build and are struggling to get forms to work. I used the same logic as I has previously: AJAX request on submit. Here’s the submit function:
function submitForm() {
if (validateForm()) {
const formData = new FormData(form);
fetch('/', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams(formData).toString()
})
.then(() => {
success = true;
})
.catch(
(error) =>
(backendError = error)
);
}
}
Other things to note:
- My page.server.js has an
export const prerender = true
- My form IS detected in the admin panel
The problem is that I get Error: 405 POST method not allowed
on submission. Now I did the obvious thing and scouted the forums to try different methods. I tried fetch('/contact.html'
, as well as fetching the favicon, for both methods I get Error: 404 Not found
. Additionally I tried placing my contact.html
inside the static folder and fetch, but same 404 error.
What am I doing wrong? Any help is greatly appreciated.
@asertym What’s the site name / URL?
Is there a public repo?
Not a public repo, I’m sorry. Site name is https://dartstudios.uk
@asertym No problem, having a closed source project is entirely understandable.
However since it requires extra time/effort to debug with lower visibility, (and I’m not super interested in playing a game of ‘20 questions’), I’m only going to make one attempt at a ‘wild guess’ answer to try and help you.
The documentation for performing an AJAX based submission is here:
https://docs.netlify.com/forms/setup/#submit-html-forms-with-ajax
You also need to read the sections below that one, as they contain additional requirements:
https://docs.netlify.com/forms/setup/#javascript-forms
https://docs.netlify.com/forms/setup/#work-with-javascript-rendered-forms
What I see:
-
Viewing source on your /
and /contact
routes indicates they are different pages.
-
The /contact
route does contain a form that appears to have been processed by Netlify.
This aligns with your assertion that it shows as detected in your Netlify UI.
-
Your form is JavaScript rendered as the one that appears is not the same as seen by ‘View Source’
-
Your form is not submitting the form-name
value, which is required:
So that’s something wrong with the form, that will be preventing it from working.
It may not be the only thing, but it’s as far as I’m willing to investigate.
To answer ‘why is it happening’…
The static version of the form, which has been processed by Netlify, has had a hidden input automatically inserted.
Your JavaScript version of the form, isn’t processed by Netlify, and does not have that hidden input.
Your submission code uses FormData
to retrieve the form values, and since the input doesn’t exist the value is never sent.
This behavior is all as per the documentation.
1 Like