Last active
April 16, 2020 23:54
-
-
Save oliverll1/d087969d4f062d9a575fac4249c3b700 to your computer and use it in GitHub Desktop.
send form with ajax (vanilla JS)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const sendForm = async function(form){ | |
let XHR = new XMLHttpRequest(); | |
let FD = new FormData(form); | |
window.location.reload(); | |
// Define what happens on successful data submission | |
XHR.addEventListener('load', function(event) { | |
console.log('Yeah! Data sent and response loaded.'); | |
}); | |
// Define what happens in case of error | |
XHR.addEventListener('error', function(event) { | |
alert('Oops! Something went wrong.'); | |
console.log('Oops! Something went wrong.'); | |
}); | |
// Set up our request | |
XHR.open('POST', form.action); | |
// Send our FormData object; HTTP headers are set automatically | |
XHR.send(FD); | |
}; | |
const submitForm = function(form){ | |
event.preventDefault(); | |
sendForm(form); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment