Last active
May 1, 2024 12:11
-
-
Save aliboy08/5bded0e50de010c4f142060fc7314ad1 to your computer and use it in GitHub Desktop.
wp ajax boilerplate with fetch
This file contains 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
<?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