PHP, MySQL, JavaScript, Windows 7, Linux
How to do Ajax calls within the WordPress administration panels
To complete a simple Ajax call within the administration panels, we will need a minimum of three functions. Here are the functions used in the sample code:
- _wp_display_content() — responsible for displaying the form or content, and the nonce field.
- _wp_display_content_js() — displays the JavaScript code for our Ajax call in the footer.
- _wp_sample_ajax_call() — completes security check for the Ajax request, processes the request, and returns a response.
/**
* How to make Ajax calls within the WP Administration Panels.
*
* @author Chris Strosser
* @version 20090822
*/
// Define the $ajax_action (should be unique).
$ajax_action = 'wp_custom_ajax_call';
/**
* Display nonce field and page/form content.
*
* @return void
*/
function _wp_display_content() {
global $ajax_action;
wp_create_nonce($ajax_action);
// Put form content or content that requires an Ajax call here...
}
/**
* This is the function that displays the JavaScript for the Ajax call.
* JavaScript can also be stored in an external file, registered as a WP
* script, and then enqueued for inclusion in the load-scripts.php file.
*
* @return void
*/
function _wp_display_content_js() {
global $ajax_action, $nonce;
?>
<script type="text/javascript">
/* <![CDATA[ */
(function($) {
$.ajax({
type: "post",
url: "admin-ajax.php",
data: {
action: '<?php echo esc_js( $ajax_action ); ?>',
_ajax_nonce: '<?php echo esc_js( $nonce ); ?>'
},
beforeSend: function() {},
complete: function() {},
success: function(response) {}
});
})(jQuery);
/* ]]> */
</script>
<?php
}
add_action('admin_print_footer_scripts', '_wp_display_content_js');
/**
* This will be called by admin-ajax.php according to the action passed.
*
* The admin-ajax.php file will execute do_action('wp_ajax_<insert action here>') if
* there aren't any preexisting calls with that name.
*/
function _wp_sample_ajax_call() {
global $ajax_action;
check_ajax_referer($ajax_action);
// The data or content to return
exit();
}
add_action('wp_ajax_' . $ajax_action, '_wp_sample_ajax_call');
October 22, 2009 - 4:06 am
i am looking fort his for admin section to use ajax if you build this as plugin it will be very useful