'Netlify AJAX form returns blank fields
I have a form in netlify, I use a function to show a notification instead of taking the user to another page after the submission. The form is recognized by Netlify and I get the submissions at my email, but it's blank. I have a static version in my html file.
function encode(data) {
return Object.keys(data)
.map(
(key) =>
encodeURIComponent(key) + "=" + encodeURIComponent(data[key])
)
.join("&")
}
function handleSubmit(e) {
e.preventDefault();
fetch("/", {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: encode({
"form-name": e.target.getAttribute('name'),
"form_name": document.getElementsByName('name')[1],
"form_email": document.getElementsByName('email')[1],
"form_body": document.getElementsByName('message')[1]
})
})
.then(() => {
if (!Response.ok) {
toast.error('Error!', {
theme: 'colored'
})
}
else {
toast.success('Message Send!', {
theme: 'colored'
})
}
})
.catch(error => toast.error('Error!' + error, {
theme: 'colored'
}));
}
return (
<form onSubmit={handleSubmit} name='contact'>
<input className='form-input' type='text' name='name' placeholder='Name' autoComplete='off' required/>
<input className='form-input' type='email' name="email" placeholder='E-Mail' autoComplete='off' required/>
<textarea className='form-input-text' name="message" placeholder='Body' required/>
<button className='form-input-button' type='submit'>SUBMIT</button>
<input type="hidden" name="form-name" value="contact" />
</form>
)
Static form in the html file:
<form name="contact" netlify netlify-honeypot="bot-field" hidden>
<input type="text" name="name">
<input type="email" name="email">
<textarea name="message"></textarea>
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
