Skip to content

Instantly share code, notes, and snippets.

@sheabunge
Last active May 22, 2022
Embed
What would you like to do?
<?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 } );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment