Skip to content

Instantly share code, notes, and snippets.

@MikeNGarrett
Created January 28, 2014 23:34
Show Gist options
  • Save MikeNGarrett/8678850 to your computer and use it in GitHub Desktop.
Save MikeNGarrett/8678850 to your computer and use it in GitHub Desktop.
Simple WordPress ajax structure example
<?php
// in functions.php
add_action('wp_ajax_testing_axaj', 'ajax_function_to_execute', 1, 2);
add_action('wp_ajax_nopriv_testing_axaj', 'ajax_function_to_execute', 1, 2);
function ajax_function_to_execute() {
print_r($_REQUEST);
die();
}
// Add your js file where you need it
add_action( 'admin_enqueue_scripts', 'enqueue_my_scripts' );
function enqueue_my_scripts($hook) {
if( 'index.php' != $hook ) {
// Do not execute in the dashboard
return;
}
wp_enqueue_script( 'my-ajax-script', plugins_url( get_stylesheet_directory_uri().'/js/my-ajax-script.js' ), array('jquery') );
?>
<?php // Recommended the following go in its own js file you enqueue with above php function ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var data = {
action: 'testing_axaj',
arbitrary_value: 'arbitrary_key'
};
$.ajax({
url: window.ajaxurl,
data: data,
async: true,
cache: false,
type: 'get',
success: function(response){
console.log('Response from server: ' + response);
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment