Created
January 28, 2014 23:34
-
-
Save MikeNGarrett/8678850 to your computer and use it in GitHub Desktop.
Simple WordPress ajax structure example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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