Five Tips for Using AJAX in WordPress
Asynchronous JavaScript and XML, or Ajax, has become very popular and is used in many WordPress themes. This popularity, however, does not necessarily mean that Ajax is being implemented correctly. There are a few tips and tricks you can utilize when working with Ajax that will ensure your WordPress site operates smoothly.
-
Check for Permissions
-
A common mistake when using Ajax in WordPress is the lack of consistency when checking for permissions. This creates a security issue because without sufficient checks, a malicious user could gain access to unauthorized areas. To ensure that each Ajax request is made by an authorized user, always use the "current_user_can()" function:
if ( current_user_can( 'edit_comments' ) )
{
// get parameters
$postID = $_POST['postID'];
}
Form Submission
-
Many developers are unaware that WordPress has its own jQuery plug-in to handle Ajax form submissions. This plug-in is accessed by using “jQuery-form” as the handle:
wp_enqueue_script( 'json-form' );
Creating a submission form that doesn't require a page refresh becomes easy:
jQuery('#Form1').ajaxForm({
dataType: 'json',
success : function(responseText, statusText, xhr, $form) {
}
}); -
Improving Security
-
Security can be bolstered with the implementation of nonces, which are numbers that are randomly generated and used only once. JavaScript can then be set to use a global variable to get the nonce. Each time a user needs to initiate an Ajax request, like editing a comment, check for the presence of that specific nonce.
Search Engine Optimization
-
Search Engine Optimization can be crucial to the success of a website, and it is often overlooked by designers. Ajax has built a reputation of not working well with search engines, and many engines encounter problems when trying to index Ajax properly. The most important design tip is to ensure that a static page and URL exists for every page iteration. For example, if a page allows the user to activate filters, make certain that the modified page points to a static URL.
Options
-
Some developers forget that Ajax does not require XML. Although JSON seems to be popular, remember there are other methods of data transport such as CVS, HTML, and encoded formats.
-
References
- Photo Credit Comstock/Comstock/Getty Images