Skip to content

Instantly share code, notes, and snippets.

@aliboy08
Last active May 1, 2024 12:11
Show Gist options
  • Save aliboy08/5bded0e50de010c4f142060fc7314ad1 to your computer and use it in GitHub Desktop.
Save aliboy08/5bded0e50de010c4f142060fc7314ad1 to your computer and use it in GitHub Desktop.
wp ajax boilerplate with fetch
<?php
add_action('wp_ajax_ACTION_HERE', function(){
$response = [
'post' => $_POST,
];
wp_send_json($response);
});
?>
<script>
(function(){
button.addEventListener('click', ajax_request)
function ajax_request(){
let form_data = new FormData();
form_data.append('action', 'ACTION_HERE');
form_data.append('custom_key', 'custom_data');
fetch( ajaxurl, { method: 'POST', body: form_data }).then(res => res.text()).then(process);
}
function process(data){
data = JSON.parse(data);
console.log('process', data)
}
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment