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
orprint_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 toWP_DEBUG_LOG
file and check the results there: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 useWP_DEBUG_LOG
;P2) Use javascript’s own
console.log()
to check the response right in your browser:Send a response from the AJAX action…
… and receive it with JS:
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!
If some other handler code is hooked first and it calls
exit()
too, then the script ends, so your code never runs.Check the other handler.