WordPress basic AJAX example. https://help.codesnippets.pro/article/48-ajax-within-snippets
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 | |
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