Skip to content

Instantly share code, notes, and snippets.

@oliverll1
Last active April 16, 2020 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oliverll1/d087969d4f062d9a575fac4249c3b700 to your computer and use it in GitHub Desktop.
Save oliverll1/d087969d4f062d9a575fac4249c3b700 to your computer and use it in GitHub Desktop.
send form with ajax (vanilla JS)
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