I was trying to add one more callback function to the WordPress AJAX action woocommerce_apply_coupon
.
This action is defined in the WooCommerce plugin, I want to add my own callback function to this action from my plugin file.
What I have tried:
add_action( 'wp_ajax_nopriv_woocommerce_apply_coupon','darn',999);
add_action( 'wp_ajax_woocommerce_apply_coupon', 'darn',999);
function darn(){
print_r($_REQUEST);
exit;
}
Doing this in my functions.php
is not even showing any error, like I can’t see any effect of this code.
I want to know if this is even possible to achieve . Thank you.
Yes. It is possible and you’re on the right track! 🙂
AJAX calls happen “behind the scenes” and no screen output is generated during the process no matter what you echo
or print_r
– that’s why you don’t see anything returned to you – instead that server response is captured by javascript and acted upon there.
That gives you two basic options for debugging your AJAX actions:
1) You can use error_log()
in your AJAX actions to write the output to WP_DEBUG_LOG
file and check the results there:
function darn(){
error_log( print_r($_POST, 1) );
exit;
}
For more details see Codex: Debugging_in_WordPress – WP_DEBUG_LOG
Pro-tip #1: Fire up a terminal console and use tail -f debug.log
for a live stream of debugging awesomness 😉
Pro-tip #2: Use tail -f debug.log | grep -v 'bad-plugin'
to filter out too much debugging awesomness from plugin authors who don’t use WP_DEBUG_LOG
;P
2) Use javascript’s own console.log()
to check the response right in your browser:
Send a response from the AJAX action…
function darn(){
echo 'darn!'
exit;
}
… and receive it with JS:
$.post(ajaxurl, data, function(response) {
// Response will be 'darn!'
if( typeof(console) == 'object' ) console.log( response );
});
Pro-tip #3: Instead of simply echoing the response like we did above you can use wp_send_json() for generating a JSON formatted response or WP_Ajax_Response class for a XML. Handy for more complex responses and/or error handling!
Pro-tip #4: Let me know in comments if anything remains unclear 😀
Welcome and have a great time on WPSE!