Skip to content

Instantly share code, notes, and snippets.

@pelukho
Created April 16, 2021 14:51
Show Gist options
  • Save pelukho/cc824603cd16ae1d65d34e5502facce4 to your computer and use it in GitHub Desktop.
Save pelukho/cc824603cd16ae1d65d34e5502facce4 to your computer and use it in GitHub Desktop.
Ajax sending data for wordpress
// document ready function
let ready = callback => {
if (document.readyState !== "loading") {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
}
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data
});
if (response.status >= 400) {
throw new Error('There was some error on the server');
}
return await response.json(); // parses JSON response into native JavaScript objects
}
ready(() => {
// get form
let form = document.getElementById('form');
form.addEventListener('submit', function (e) {
e.preventDefault();
let $this = this,
formData = new FormData($this);
// adding action name
formData.append('action', 'send_ajax');
// adding nonce
formData.append('nonce', myajax.nonce);
const data = new URLSearchParams(formData);
postData(myajax.url, data)
.then(resp => {
if (resp.success) {
let {name, email, text} = resp.data;
alert(`
Your name: ${name}
Your email: ${email}
Your text: ${text}
`);
$this.reset();
}
})
.catch(error => {
console.error(error);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment