Skip to content

Instantly share code, notes, and snippets.

@sheabunge
Last active February 16, 2024 17:55
Show Gist options
  • Save sheabunge/f8f4b244f5e97aae8e195908c7555fed to your computer and use it in GitHub Desktop.
Save sheabunge/f8f4b244f5e97aae8e195908c7555fed to your computer and use it in GitHub Desktop.
<?php
const ACTION_NAME = 'shea_ajax_example';
$handler = function () {
check_ajax_referer( ACTION_NAME );
wp_send_json_success( 'it works!' );
};
add_action( 'wp_ajax_' . ACTION_NAME, $handler );
add_action( 'wp_ajax_nopriv_' . ACTION_NAME, $handler );
add_shortcode( 'shea_ajax_button', function () {
return '<button id="shea-ajax-button">Click me for AJAX</button>';
} );
add_action( 'wp_footer', function () {
$data = [
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'action' => ACTION_NAME,
'nonce' => wp_create_nonce( ACTION_NAME ),
];
?>
<script>
const data = <?php echo wp_json_encode( $data ); ?>;
const ajaxButton = document.getElementById('shea-ajax-button');
ajaxButton.addEventListener('click', () => {
const request = new XMLHttpRequest();
request.open('POST', data.ajaxurl, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = () => {
if (200 > request.status || 400 <= request.status) {
alert('AJAX failure :( We received error code ' + request.status);
return;
}
const response = JSON.parse(request.responseText)
alert('AJAX success! Message: ' + response.data);
};
request.send(`action=${data.action}&_ajax_nonce=${data.nonce}`);
});
</script>
<?php } );
@sander45
Copy link

Thank you for your explanation and the provided code. I would have hoped to find it earlier, as combining AJAX with a snippet is not that difficult after all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment