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!