Post Comments with Ajax in WordPress

I use this code to post comments with ajax on my WP blog. It works fine but I display the comment form on my homepage so the plugin only works for the first post (first comment form).

I want it to work for all the forms.

Read More

Here is my code:

if (typeof jQuery != 'undefined') {
  jQuery('document').ready(function($){
    var commentform=$('#commentform');
    commentform.prepend('<div id="comment-status" ></div>');

    var statusdiv=$('#comment-status');

    commentform.submit(function(){
      var formdata=commentform.serialize();
      statusdiv.html('<p>Processing...</p>');

      var formurl=commentform.attr('action');

      $.ajax({
        type: 'post',
        url: formurl,
        data: formdata,
        error: function(XMLHttpRequest, textStatus, errorThrown){
          statusdiv.html('<p class="wdpajax-error" >You might have left one of the fields blank, or be posting too quickly</p>');
        },
        success: function(data, textStatus){
          if(data=="success")
            statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
          else
            statusdiv.html('<p class="ajax-error" >Please wait a while before posting your next comment</p>');
            commentform.find('textarea[name=comment]').val('');
        }
      });

      return false; 
    });
  });
}

Related posts

Leave a Reply