Resolving the Random Zero at the End of AJAX Requests in WordPress
If you’ve ever integrated AJAX functionality into a WordPress plugin or theme, you have probably / should have used the in-built WordPress functionality that already exists. An article in the WordPress Codex explains how to do this, and demonstrates how easy it can be.
I needed to do exactly this today; Add an AJAX request to a theme in order to dynamically load some content. I followed the instructions from the Codex article and, hey presto, it worked. The AJAX request was made, and I got the data back that I expected via a call to a function in the theme’s functions.php file.
After looking a little closer, I noticed that I was getting a random ‘0’ (zero) character output at the end of the response from the AJAX request.
After a bit of debugging and searching around I found the cause and, more importantly, the solution.
Don’t worry, the additional zero being output isn’t a typo on your behalf. It’s the default response from all AJAX responses in WordPress. If you take a look at the bottom of the wp-admin/admin-ajax.php file in your site you’ll notice the following:
// Default status die( '0' );
So that would explain the extra zero, but how do we stop it?
Fortunately the solution is a simple one. Simply make a call to the PHP functions die() or exit() at the bottom of your response. This will then mean that it never reaches the default WordPress output.
If you take a look at the Codex page originally linked to at the beginning of this post, you’ll notice that they are making a call to the die() function once they’ve completed their output.