Skip to content

Instantly share code, notes, and snippets.

@pavr0m
Last active March 12, 2020 13:47
Show Gist options
  • Save pavr0m/f4f14a38adb5c7ce99f6364c39d89a3e to your computer and use it in GitHub Desktop.
Save pavr0m/f4f14a38adb5c7ce99f6364c39d89a3e to your computer and use it in GitHub Desktop.
Wordpress template ajax callback
<?php
/**
* Template ajax callback
*/
add_action( 'wp_ajax_callback', 'callback' );
add_action( 'wp_ajax_nopriv_callback', 'callback' );
function callback($a) {
$data = dosomething($a);
$data = json_encode($data);
wp_die($data);
}
add_action('wp_footer', 'template_ajax_call_js');
function template_ajax_call_js() {
ob_start();?>
<script>
jQuery(function($) {
// Template ajax call
$.ajax({
url: ajaxurl, // supply ajax url
data: {
'action': 'callback',
'input' : 'somevalue'
},
success:function(data) {
console.log(data);
},
error: function(errorThrown){
alert('error');
console.log(errorThrown);
}
});
});
</script>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment