Skip to content

Instantly share code, notes, and snippets.

@juanbrujo juanbrujo/form-netlify.css
Last active Jun 20, 2019

Embed
What would you like to do?
JS function to send by AJAX a form data to Netlify Forms
.result {
display: none;
}
.active {
display: block;
}
.inactive {
display: none;
}
<form class="my-form" name="form-name" netlify>
<input type="text" placeholder="Your name" id="name-field" name="name-field" required>
...
</form>
<div class="result post-sent">
<h3>Success!</h3>
</div>
<div class="result post-error">
<h3>Error...</h3>
</div>
function sendFormData() {
function sendData() {
var XHR = new XMLHttpRequest()
var FD = new FormData(form)
XHR.addEventListener('load', function(event) {
form.classList.add('inactive')
var success = document.querySelectorAll('.post-sent')[0]
success.classList.add('active')
})
XHR.addEventListener('error', function(event) {
form.classList.add('inactive')
var error = document.querySelectorAll('.post-error')[0]
error.classList.add('active')
})
XHR.open('POST', '#')
XHR.send(FD)
}
var form = document.querySelectorAll('.my-form')[0]
form.addEventListener('submit', function (e) {
e.preventDefault()
sendData()
})
}
export default sendFormData
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.