Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/*
Plugin Name: WP Testing Admin AJAX
Plugin URI: https://pakaiwp.com/
Description: Testing AJAX pada wp-admin dashboard
Author: Pakai WP
Version: 1
Author URI: https://pakaiwp.com/
*/
// Buat contoh halaman admin
add_action('admin_menu', 'wp_testing_admin_ajax_page');
function wp_testing_admin_ajax_page() {
add_menu_page('Admin AJAX', 'Admin AJAX', 'manage_options', 'admin-ajax', 'wp_testing_admin_ajax_content', 'dashicons-chart-pie', 2);
}
// Fungsi halaman
function wp_testing_admin_ajax_content() {
global $hook_suffix;
?>
<div class="wrap">
<h1><?php echo esc_html(get_admin_page_title()); ?></h1>
<hr>
<p><strong>Hook Suffix:</strong> : <?php echo $hook_suffix; ?></p>
<p>Ketika tombol di klik, maka akan melakukan request AJAX untuk mendapatkan info email administrator website.</p>
<button id="info-email" class="button">Info Email Admin Website</button>
<span class="spinner" style="float:none;"></span>
</div>
<?php }
// Fungsi script javascript pada admin footer menggunakan hook suffix
add_action('admin_footer-toplevel_page_admin-ajax', 'wp_testing_admin_ajax_script');
function wp_testing_admin_ajax_script() { ?>
<script>
jQuery(document).on('click', '#info-email', function() {
jQuery.ajax({
url: ajaxurl, // secara otomatis menuju admin-ajax.php
type: 'GET', // Ubah mau ajax GET/POST
data: {
'action': 'wp_test_admin_ajax'
},
beforeSend: function() {
jQuery('.spinner').addClass('is-active');
},
complete: function() {
jQuery('.spinner').removeClass('is-active');
},
success: function(response) {
alert(response);
console.log(response);
}
});
});
</script>
<?php }
// Fungsi ajax pada admin
add_action('wp_ajax_wp_test_admin_ajax', 'wp_test_admin_ajax_response');
function wp_test_admin_ajax_response() {
echo get_bloginfo('admin_email');
wp_die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment