AJAX WordPress Comments: Enhance User Experience

Improving WordPress Commenting with AJAX
The standard WordPress commenting functionality often falls short of modern user expectations. A significant drawback is the page refresh required after submitting a comment, disrupting the user experience.
While alternatives like Livefyre or Disqus exist, integrating a solution directly within WordPress offers greater control and customization.
Implementing AJAX for comment posting is a fundamental improvement you should consider.
The Benefits of AJAX Comments
An AJAX-based commenting system, as demonstrated on MakeUseOf, allows users to submit comments without a page reload.
Instead, the comment is sent via an AJAX request, and a confirmation message is displayed, providing a seamless and responsive experience.
Prerequisites and Further Reading
If you intend to utilize functions outside of the standard WordPress framework with AJAX, it’s important to familiarize yourself with the necessary techniques.
Refer to my earlier tutorial for guidance on using non-WordPress functions in AJAX implementations.
Additionally, explore the full range of WordPress-related articles available for a comprehensive understanding of the platform’s capabilities.
This approach ensures a more fluid and engaging interaction for your website visitors.
Understanding AJAX WordPress Comments
Implementing AJAX functionality for WordPress comments requires two distinct components. Let's begin by outlining these elements to provide a comprehensive understanding of the overall process.
Key Components
- Client-side Javascript is necessary to intercept the submission of comments.
- This Javascript must convert the standard form submission into an AJAX request.
- It also needs to effectively manage the response received from the server.
- A server-side PHP handler is required to process the comment submission.
- This handler integrates with the
comment_postaction hook within WordPress.
These two parts work in tandem to create a seamless, asynchronous comment submission experience for users.
Javascript Implementation
The Javascript component plays a crucial role in enhancing user interaction. It intercepts the default form submission behavior.
Javascript Functions
- Upon a user clicking the "Add Comment" button, the Javascript code intervenes.
- It prevents the standard page reload associated with a typical form submission.
- Instead, an AJAX request is initiated, sending the comment data to the server.
- The response from the server is then handled by the Javascript, updating the comment section dynamically.
This approach provides a more responsive and user-friendly experience, as users don't have to wait for a full page refresh to see their comments appear.
PHP Handler Details
The PHP handler is responsible for the server-side processing of the submitted comment.
PHP Integration
- The PHP script is designed to hook into the
comment_postaction. - This action is triggered when a user attempts to submit a comment.
- Within the handler, the comment data is validated and sanitized.
- The comment is then saved to the WordPress database.
- Finally, a response is sent back to the Javascript, indicating success or failure.
Properly securing the PHP handler is paramount to prevent malicious attacks and ensure data integrity.
Conclusion
Successfully implementing AJAX WordPress comments involves a coordinated effort between client-side Javascript and server-side PHP.
By intercepting form submissions with Javascript and processing them asynchronously through a PHP handler, a more dynamic and engaging commenting system can be achieved. This enhances the user experience and provides a modern feel to your WordPress website.
Javascript
Initially, jQuery is required for this implementation, much like with many advanced web development features. If you are uncertain whether jQuery is already included, proceed to the Javascript code and test it. Should the console log display "jQuery is undefined" upon page refresh, incorporate the following code snippet into your functions.php file to guarantee its loading.
function google_jquery() { if ( !is_admin() ) { wp_deregister_script('jquery'); wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"), false);
wp_enqueue_script('jquery'); } }
add_action('wp_print_scripts ', 'google_jquery');
It's worth noting that this approach loads jQuery from Google's CDNs, offering faster loading times and a more current version compared to the default WordPress inclusion. Therefore, adding this may be beneficial even if jQuery is already loaded through another source.
Now, turning to the Javascript code responsible for managing the comment form, several options exist for its integration. The simplest method involves directly pasting the code into your single.php template, assuming commenting is not enabled on pages.
Alternatively, the code can be added to an existing .js file utilized by your theme, or a new .js file can be created within your theme directory. If opting for a separate .js file – assumed to be named ajaxcomments.js located in the root of your theme folder – ensure the following lines are added to your functions.php file.
add_action('init', 'ajaxcomments_load_js', 10); function ajaxcomments_load_js(){
wp_enqueue_script('ajaxcomments', get_stylesheet_directory_uri().'/ajaxcomments.js');
}
The following Javascript code handles the comment form functionality (or it can be viewed on pastebin):
<script type="text/javascript">
// AJAXified commenting systemjQuery('document').ready(function($){
var commentform=$('#commentform'); // Locate the comment form
commentform.prepend('<div id="comment-status" ></div>'); // Insert an information panel before the form for feedback
var statusdiv=$('#comment-status'); // Define the information panel
commentform.submit(function(){
//Serialize and store the form data
var formdata=commentform.serialize();
//Display a status message
statusdiv.html('<p>Processing...</p>');
//Retrieve the form's action URL
var formurl=commentform.attr('action');
//Submit the form data via AJAX
$.ajax({
type: 'post',
url: formurl,
data: formdata,
error: function(XMLHttpRequest, textStatus, errorThrown){
statusdiv.html('<p class="wdpajax-error" >You may have left a field blank, or are submitting too rapidly</p>');
},
success: function(data, textStatus){
if(data=="success")
statusdiv.html('<p class="ajax-success" >Thank you for your comment. Your input is valued.</p>');
else
statusdiv.html('<p class="ajax-error" >Please wait before submitting another comment</p>');
commentform.find('textarea[name=comment]').val('');
}
});
return false;
});
});</script>
Breaking down the code, we begin by creating jQuery objects representing the comment form – assuming it has the standard CSS ID of "commentform" – and adding an empty information panel above it. This panel will be used to display messages to the user regarding the comment submission process.
The commentform.submit function intercepts the submit button's action. The form data is then serialized, a "Processing" message is displayed in the information panel, and an AJAX request is initiated. This request, while standard in format, is beyond the scope of this tutorial. It responds to either success or failure, clearing the form upon successful submission to prevent accidental duplicates. Feel free to customize the messages and add styling to your theme's stylesheet to enhance the visibility of error messages. Finally, return false prevents the form's default submission behavior.
PHP Handler for AJAX Comments
A crucial component involves preventing page reloads and delivering the correct response to the user. This also includes informing the administrator about comments requiring moderation, or alerting the post author of new submissions. To achieve this, we utilize the comment_post action hook.
This hook is triggered immediately after a comment is saved to the database, and we leverage it to identify AJAX requests. The following code should be added to your functions.php file:
(The code is also accessible on this pastebin)
Code Implementation
The following PHP function handles the AJAX comment submission process. It checks for an AJAX request and then processes the comment based on its status.
add_action('comment_post', 'ajaxify_comments', 20, 2);function ajaxify_comments($comment_ID, $comment_status){
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
//Processing an AJAX Request
switch($comment_status){
case '0':
//Alert moderator about pending comment
wp_notify_moderator($comment_ID);
case '1': //Comment has been approved
echo "success";
$commentdata=&get_comment($comment_ID, ARRAY_A);
$post=&get_post($commentdata['comment_post_ID']);
wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
break;
default:
echo "error";
}
exit;
}
}
Function Breakdown
The ajaxify_comments function receives the comment ID and its status as arguments. It first verifies that the request originates from an AJAX call.
A switch statement then handles different comment statuses. If the comment is pending moderation (status '0'), the moderator is notified.
If the comment is approved (status '1'), a "success" message is echoed, and the post author is notified. The function retrieves comment and post data for notification purposes.
In case of any other status, an "error" message is echoed, and the script terminates to prevent further processing.
Troubleshooting Refreshing Issues
Should the page continue to reload rather than submit via AJAX, the cause is likely one of two issues. First, jQuery may not be properly included. Utilize Firebug or the Chrome developer tools to inspect the console log for any error messages.
If jQuery is not detected, revisit the JavaScript instructions and review the section detailing its addition to your theme. Alternatively, the issue could stem from modifications your theme applies to the comment form.
Identifying the Comment Form ID
Specifically, the comment form's ID might no longer be "commentform". Examine the page source code to determine the current ID.
Once identified, adjust the JavaScript line var commentform=$('#commentform') to reflect the correct ID; this adjustment may resolve the problem.
I remain available to provide further assistance where possible. However, please include a link to a relevant URL so I can quickly assess the situation.