Skip to content

Instantly share code, notes, and snippets.

@juanbrujo
Last active September 4, 2022 19:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanbrujo/c97afee62975bddc0ab9e4428a39f474 to your computer and use it in GitHub Desktop.
Save juanbrujo/c97afee62975bddc0ab9e4428a39f474 to your computer and use it in GitHub Desktop.
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
@iaminamcom
Copy link

This is nice have you tested it for long forms?

@juanbrujo
Copy link
Author

no but it shouldn't have problems at all

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment