Here’s a base snippet I use for AJAX submits in WordPress. It does use jQuery, but there’s no reason vanilla won’t work.
You could admin_enqueue_scripts()
the <script>
, and conditionalize it on the proper page with get_current_screen()
.
add_action( 'admin_menu', function(){
add_menu_page( 'My Plugin', 'My Plugin', 'manage_options', 'my_plugin_slug', 'my_plugin_page', 'dashicons-cloud' );
});
function my_plugin_page() {
if (isset($_POST['my_plugin_ajax_submit']))
if ( wp_verify_nonce( $_POST['nonce'], 'my_plugin_ajax_submit' ) )
my_plugin_ajax_submit();
?>
<button id='buildButton'>Do Something</button>
<script>
jQuery('#buildButton').click(function(){
jQuery.ajax({
type: 'post',
data: {
"my_plugin_ajax_submit": "now",
"nonce" : "<?php echo wp_create_nonce( 'my_plugin_ajax_submit' ); ?>"
},
success: function(response) {
jQuery('#buildButton').text("Somthing Done!");
},
error: function(response) {
jQuery('#buildButton').text("...error!");
},
});
});
</script>
<?php
}
function my_plugin_ajax_submit() {
// some php code that fires from AJAX click of #buildButton
wp_mail( '[email protected]', 'my_plugin_ajax_submit() fired', time());
return true;
}