Below is the complete code on how to do it. For more details you may like to see how admin ajax work on codex.
<?php
/* Your code to add menu on admin bar */
add_action('admin_bar_menu', 'add_item', 100);
function add_item( $admin_bar ){
global $pagenow;
$admin_bar->add_menu( array( 'id'=>'cache-purge','title'=>'Cache Purge','href'=>'#' ) );
}
/* Here you trigger the ajax handler function using jQuery */
add_action( 'admin_footer', 'cache_purge_action_js' );
function cache_purge_action_js() { ?>
<script type="text/javascript" >
jQuery("li#wp-admin-bar-cache-purge .ab-item").on( "click", function() {
var data = {
'action': 'example_cache_purge',
};
/* since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php */
jQuery.post(ajaxurl, data, function(response) {
alert( response );
});
});
</script> <?php
}
/* Here you hook and define ajax handler function */
add_action( 'wp_ajax_example_cache_purge', 'example_cache_purge_callback' );
function example_cache_purge_callback() {
global $wpdb; /* this is how you get access to the database */
/* You cache purge logic should go here. */
$response = "Cache Purged !";
echo $response;
wp_die(); /* this is required to terminate immediately and return a proper response */
}
?>