AJAX is used in many WordPress themes and plugins. However, not all of those themes and plugins implement AJAX properly. This article reveals 5 best practices in developing AJAX for WordPress.
Warning: This is a long and information-packed article. Be sure to bookmark this post so you can always go back for reference! The links below makes it easier to navigate this article.
Table of Content
- Bad ways to implement AJAX
- 2. Use admin-ajax.php to handle AJAX requests
- 3. Use nonces and check for permission
- 4. Use the built-in jQuery Form plugin to submit forms
- 5. Be careful with jQuery default JSON parsing
Bad ways to implement AJAX
The PHP file that handles the AJAX almost always begin with this line:
What’s wrong with this is that sometimes users set up their folder structure differently, making the relative path declared in the PHP file above invalid. Another downside to this, is if you’re using Object Oriented approach to develop your plugin (wrapping your plugin functions in a class), you won’t have direct access to the necessary properties and private functions of the class.
Sorry for keeping you off the good part of the article so long. But avoiding doing things the wrong way is as important as knowing how to do them right. Without further ado, here are 5 crucial tips for implementing AJAX in WordPress properly.
Here’s how you should declare the URL to the file that handles AJAX (in this example, I use admin-ajax.php, which is discussed in tip #2):
<head> element, you’ll find this:
Now, in your
ajax.js file, you can use
MyAjax.ajaxurl without having to resort to PHP and including
2. Use admin-ajax.php to handle AJAX requests
AJAX requests should be directed to
wp-admin/admin-ajax.php. I know the “admin” part of the file name is a bit misleading, but all requests in the front-end (the viewing side) as well as the admin panel can be processed in
There’s a required parameter for a request sent to
admin-ajax : it’s called
action. This parameter is necessary because when
admin-ajax process the request, it will fire one of these hooks, depending on whether the current viewer is logged in or not:
Now all we have to do is hook our existing plugin or theme file up with those provided ajax actions without having to create a separate file to process the request:
3. Use nonces and check for permission
It can’t be stressed enough that you need to check for permission for every action a user takes. Developers often neglect this, and the results are disastrous, because without layers that checks for sufficient permissions, a malicious user could escalate his privilege and do all sorts of naughty things with your website that you have spent so much effort to build. There are two layers of security that you need to apply to all AJAX request most of the time.
Nonces are Numbers that are generated and used once. Nonces are used to make sure the action is initiated by the authorized user from a certain location. Here’s an interesting analogy by Jon Sykes, which makes everything easier to understand:
When you arrive at a deli counter you’re asked to take a ticket. Once the counter reaches your number you had the ticket back to the server (who throws it away) and they serve you. They then move onto serving the next person in the who’s ticket matches the number of the digital screen.
If someone comes along and tries to jump the line (queue) they can’t unless they have a ticket.
If they manage to get hold of someones old ticket, they can’t use it, as it’s already been used and the digital counter has moved on.
To further extend the analogy, you then make every customer sign for the ticket when they take one, and you then check not only that there ticket matches but also make them sign again to check that their first signature matches the one they have before they get served.
Taking it to a silly level, you’d only allow users to get a ticket when they walked in the front door of the store (that they have to sign for). This then prevents someone climbing in a window and trying to forge your signature to get served. Because they didn’t come in the front door, they don’t have any access to the tickets, so they have no way of jumping ahead of you and ordering the last of the Bologna.
Mark Jaquith and Vladimir Prelovac also covered Nonces and how to use them generally. Make sure you read those articles because you’ll definitely need them for almost all kinds of WP development (not only AJAX related).
However, it should be stressed that nonces are useful only in situations where the AJAX request has something to do with data or content manipulation. If the request is only for retrieving comment count, or post content for example, nonces are not required. AJAX requests to post / edit / delete contents definitely need nonce checking.
OK, enough theory. Here’s how to implement nonces in your AJAX request.
First, you need to generate a nonce, and use
MyAjax.postCommentNonce to get the nonce. You have to send the nonce along with your request so that the AJAX handler can check it:
Here’s essentially the same code as in tip #2, except that I’ve added nonce validation to make sure the request is valid:
<script src="https://gist.github.com/3827596.js"> </script>
There, all done. Now here’s an important note. If you want to allow the user to initiate the AJAX request multiple times (like posting multiple comments on the same page) , you need to regenerate a new nonce, include it in your response, and then reassign that new nonce to MyAjax.postCommentNonce. Otherwise, the same nonce would be used over and over again, and the subsequent AJAX requests will fail.
Check for permissions
Lots of plugins neglect to check for sufficient permission for AJAX requests. Always use
current_user_can() to make sure the request is made by an authorized user. Here’s the final bulletproofed version of the request handling code:
4. Use the built-in jQuery Form plugin to submit forms
Most of the time you use AJAX to avoid page reload when submitting forms. Not everyone knows that WordPress also provide a jQuery plugin to deal with AJAX form submission. To use this jQuery plugin, include it by using “jquery-form” as the handle:
Then, submitting form using AJAX is a breeze:
There are a lot more options for you to configure. Check out jQuery Form plugin documentation for more details.
5. Be careful with jQuery default JSON parsing
At the moment of this writing, the latest stable version of WordPress is 2.9.2 . In this version of WordPress, the default jQuery version is 1.3.2 .
In jQuery 1.3.2 or earlier, jQuery uses
eval to convert a JSON string into an object. While this is fast, it’s not safe:
jQuery 1.3.3 and later will automatically check if there’s already a JSON parser, and use that parser instead of
wp-includes/js/json2.js. Including it is simple:
Then, to make sure your script parses JSON the safe way, there are two ways:
The first way is to include your own version of jQuery (equal or later than 1.3.3)
The second way is to use WordPress supplied jQuery, but make sure that you don’t specify “json” as the response type, and use the included JSON parser to do the dirty job. You need to set the dependency first:
Then use JSON parser to parse the response string:
AJAX makes interaction with users more smooth and responsive, and is highly recommended for consideration when you develop your own plugins or themes. However, it’s vital that AJAX is implemented correctly and securely, otherwise the consequence could be disastrous. This article covers 5 most essential tips that all serious WordPress developers should employ to make sure their AJAX plugins or themes function well and safe.
Do you have other AJAX tips or tricks that you want to share? Drop in a comment below. Your input is always appreciated!