How To: AJAXify WordPress Comment Posting

There are tons of WordPress Tutorials out there, but i haven’t found a single one that explains how to AJAX-ify WordPress comment posting on blog posts. Though there are some plugins for AJAX comments, but none seem to work with WordPress 2.8 or later versions.

Today i will show you how to enable AJAX comments with client side JavaScript comment form validation on your WordPress blog step by step that should work with most versions of WordPress. We’ll be modifying the WordPress theme files to do that. In few days, i’ll be releasing a WordPress plugin that will automatically enable AJAX Comments. So, do subscribe to our RSS Feed or e-mail updates so that you are the first to know about it.

Let’s start with it.

Functions.php file

Add the following lines of code to your theme’s functions.php file. If your theme doesn’t have one, then create a new file and add it to your theme folder.

add_action('init', 'wdp_ajaxcomments_load_js', 10);
function wdp_ajaxcomments_load_js(){
		wp_enqueue_script('ajaxValidate', get_stylesheet_directory_uri().'/wdp-ajaxed-comments/js/jquery.validate.min.js', array('jquery'), '1.5.5');
		wp_enqueue_script('ajaxcomments', get_stylesheet_directory_uri().'/wdp-ajaxed-comments/js/ajax-comments.js',	array('jquery', 'ajaxValidate'), '1.1');
}
add_action('comment_post', 'wdp_ajaxcomments_stop_for_ajax',20, 2);
function wdp_ajaxcomments_stop_for_ajax($comment_ID, $comment_status){
	if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
	//If AJAX Request Then
		switch($comment_status){
			case '0':
				//notify moderator of unapproved comment
				wp_notify_moderator($comment_ID);
			case '1': //Approved comment
				echo "success";
				$commentdata=&get_comment($comment_ID, ARRAY_A);
				$post=&get_post($commentdata['comment_post_ID']); //Notify post author of comment
				if ( get_option('comments_notify') && $commentdata['comment_approved'] && $post->post_author != $commentdata['user_ID'] )
					wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
				break;
			default:
				echo "error";
		}	
		exit;
	}
}

Code Explanation: Firstly, we load required JavaScript files jQuery, jQuery Validation and ajax-comments.js using the wp_enqueue_script() function. wp_enqueue_script() accepts four parameters.

  • First is the name of the handler for JavaScript file, you can use any name here for your own custom JavaScript, but for files that wordpress include by default like jQuery, there are pre-fixed handlers like ‘jquery’.
  • Second parameter is path to JavaScript file.
  • Third parameter is the array of name of handlers of JavaScript files, which must be loaded before the specified file.
  • Last is the version number of JavaScript file which you should use in case you use caching on your blog.

The function wdp_ajaxcomments_stop_for_ajax() hooks onto the comment_post action which is triggered after a comment has been successfully added to the database. normally, what happens when you post a comment is that you are redirected back to the original post, but since we will be using AJAX, we don’t want a redirect but a message about the status of comment posted.

I recently read a nice post from David Walsh where he told about how to identify AJAX requests using $_SERVER["HTTP_X_REQUESTED_WITH"] which is populated by most JavaScript frameworks like in our case jQuery.
I used it to hook into comment_post and check whether it is AJAX request or normal request. If it is AJAX request then check the status of comment, if it is unapproved or approved, a message ‘success’ is output and moderator or post author is notified accordingly.
After identifying AJAX request, i stopped the script execution using exit statement so as to prevent the redirect.
Now rest is the job of JavaScript code.

The JavaScript Code

You will need to add two JavaScript files jquery.validate.min.js and ajax-comments.js in the js directory of your theme(Files are available at the end of article). Create the js directory and add files if it does not exist. Though jQuery is required to work, but since it is included in WordPress by default, it will automatically be loaded as we specified it as a requirement while loading JavaScript files in functions.php.

jQuery Validation plugin is used to validate comment form data.
Here’s the code and explanation for ajax-comments.js.

jQuery('document').ready(function($){
	var commentform=$('form[action$=wp-comments-post.php]');
	commentform.prepend('<div id="wdpajax-info" ></div>');
	var infodiv=$('#wdpajax-info');
	commentform.validate({
		submitHandler: function(form){
			//serialize and store form data in a variable
			var formdata=commentform.serialize();
			//Add a status message
			infodiv.html('<p>Processing...</p>');
			//Extract action URL from commentform
			var formurl=commentform.attr('action');
			//Post Form with data
			$.ajax({
				type: 'post',
				url: formurl,
				data: formdata,
				error: function(XMLHttpRequest, textStatus, errorThrown){
					infodiv.html('<p class="wdpajax-error" >You might have left one of the fields blank.</p>');
				},
				success: function(data, textStatus){
					if(data=="success")
						infodiv.html('<p class="wdpajax-success" >Thanks for your comment. We appreciate your response.</p>');
					else
						infodiv.html('<p class="wdpajax-error" >Error in processing your form.</p>');
					commentform.find('textarea[name=comment]').val('');
				}
			});
		}
	});
});

Code Explanation: Firstly, we append a div to comment form that will show AJAX status messages. Then we intialize jQuery Validation on comment form and if validation is successful, we will use jQuery AJAX to send the form data to the action URL of comment form and display a message accordingly.

Now, uptill here, if you have followed along and worked as told, you’ll find that AJAX comment posting works but validation doesn’t. Since, we are using jQuery Validation plugin, you will have to now edit the theme’s comments.php file.

Enable Comment Form Validation

Open your theme’s comments.php and add some CSS classes to comment form input fields as described:

  • To comment author name input, add class="required"
  • To comment author email input, add class="required email"
  • To comment author URL input, add class="url"
  • To the comment textarea, add class="required"

Now the comment form validation should work. But it might be having awkward looks or styles, now the last step is to customize the looks of messages using CSS.

Customize the Styles of Messaages

The error messages from validation use labels with CSS class error. While the AJAX post request status messages use two CSS classes, wdpajax-success for AJAX success and wdpajax-error for error message. Define the styles for these classes in your theme’s stylesheet file. Here’s what i have used:

.wdpajax-error{ 
	border:1px solid #f9d9c9; 
	padding:5px; 
	color:#ff3311; 
}
.wdpajax-success{ 
	border:1px solid #339933; 
	padding:5px; 
	color:#339933; 
}
label.error{ 
	float:none !important; 
	padding-left:5px; 
	color:#ff3311; 
}

There you are with cool AJAX comments on your WordPress Blog.

 

Plugin

If you find modifying theme file difficult, or if you regularly change your blog’s theme then it will be difficult for you to modify theme files every-time you apply a new theme. so, i have created a plugin named WDP AJAX Comments that will automatically add AJAX commenting to your blog.

Enjoy!