Aslam Doctor

How to debug WordPress ajax requests?

How to debug WordPress ajax requests?

While working with WordPress Ajax requests, it’s a very tedious task to debug the response of the request. Most of the time what we do is, open the browser’s DevTools and see if there are any errors on the console. Another similar way to test the ajax response is to check the Network tab in the DevTools and click on the specific request shown there and see what response you get.

The problem is when you have any kind of PHP error in WordPress ajax request, the response will always show zero (0) as output and no error message. And that’s when we become clueless.

One simple way to overcome this problem is to simply call this Ajax method on init Hook. Below code will show you how it is done.

<?php
// Actual Ajax request code
add_action( 'wp_ajax_get_random_posts', 'get_random_posts' );
	function get_random_posts() {
		$posts = new WP_Query(
			array(
				'post_type'      => array( 'post' ),
				'posts_per_page' => '3',
				'post_status'    => array( 'publish' ),
				'orderby'        => 'rand'
			)
		);

		if ( $posts->have_posts() ) :
			while ( $posts->have_posts() ) :
				$posts->the_post();
				the_title();
				echo '<br/>';
			endwhile;
		endif;

	die();
}

// Call it on `init` hook
add_action('init',function() {
	if(isset($_GET['dotest']) )
		get_random_posts();
	}
});

In the above example, I have created an Ajax request code that fetches random 3 blog posts and shows them. Now to test this event, if we open the website using the below URL, the init hook will show the output of this request.

https://mywebsite.com/?dotest=1

This will either list 3 random posts or if there are any errors in your get_random_posts() method, it will show the errors instead of showing zero.