Last active
March 12, 2020 13:47
-
-
Save pavr0m/f4f14a38adb5c7ce99f6364c39d89a3e to your computer and use it in GitHub Desktop.
Wordpress template ajax callback
This file contains 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 | |
/** | |
* 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