Home > Web Front-end > JS Tutorial > body text

Implementation example of using AJAX technology to submit comments in WordPress_javascript skills

WBOY
Release: 2016-05-16 15:20:21
Original
1726 people have browsed it

I have always been interested in the research on Ajax interaction in WordPress, and I have always paid attention to this technology. When talking about WordPress Ajax, I have to talk about comment Ajax submission. As a blog and forum comment, Ajax submission can not only improve the user experience. , and can also significantly reduce server expenses. After all, it is much simpler to output a single comment than to reorganize and output a page. Although the number of visits has been relatively low now and there is no problem of server pressure, I, who have always paid attention to user experience, certainly cannot give up such an opportunity to improve user experience. I spent an afternoon today and completed the preliminary submission of Ajax comments on this theme.

Go straight to the point and get to the code: (principles and ideas at the end)
Please adjust the following code according to the different structure of your own theme.

WordPress Ajax Submit Comment PHP Code
Add the following section to the theme function.php file.

//以下大部分代码出自 yinheli 经由该部分代码,排除部分错误、优化精简得出以下代码。
//yinheli博客不做了,所以这里就不给链接了。
//Edited by XiangZi DEC.17TH 2011
function fail($s) {//虚拟错误头部分
  header('HTTP/1.0 500 Internal Server Error');
  echo $s;
  exit;
}
function ajax_post_comment_slow (){
 fail('用不用说这么快?想好了再说!');
}
//评论太快输出代码。
add_filter('comment_flood_trigger','ajax_post_comment_slow', 0);
//挂一个评论太快,返回内容的钩子
function ajax_comment(){
// Ajax php 响应部分代码
if($_POST['action'] == 'ajax_comment') {
  global $wpdb, $db_check;
    // Check DB
    if(!$wpdb->dbh) {
      echo('Our database has issues. Try again later.');
  die();
    } 
nocache_headers();
$comment_post_ID = (int) $_POST['comment_post_ID'];
 $status = $wpdb->get_row("SELECT post_status, comment_status FROM $wpdb->posts WHERE ID = '$comment_post_ID'");
if ( empty($status->comment_status) ) {
//这一套判断貌似抄的 wp 源代码 。详见:include/comment.php
  do_action('comment_id_not_found', $comment_post_ID);
  fail('The post you are trying to comment on does not currently exist in the database.');
} elseif ( 'closed' == $status->comment_status ) {
  do_action('comment_closed', $comment_post_ID);;
  fail('Sorry, comments are closed for this item.');
} elseif ( in_array($status->post_status, array('draft', 'pending') ) ) {
  do_action('comment_on_draft', $comment_post_ID);
  fail('The post you are trying to comment on has not been published.');
}
$comment_author    = trim(strip_tags($_POST['author']));
$comment_author_email = trim($_POST['email']);
$comment_author_url  = trim($_POST['url']);
$comment_content   = trim($_POST['comment']);
// If the user is logged in
$user = wp_get_current_user();
if ( $user->ID ) {
  $comment_author    = $wpdb->escape($user->display_name);
  $comment_author_email = $wpdb->escape($user->user_email);
  $comment_author_url  = $wpdb->escape($user->user_url);
  if ( current_user_can('unfiltered_html') ) {
    if ( wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment'] ) {
      kses_remove_filters(); // start with a clean slate
      kses_init_filters(); // set up the filters
    }
  }
} else {
  if ( get_option('comment_registration') )
    fail('火星人?注册个?');
}
$comment_type = '';
if ( get_option('require_name_email') && !$user->ID ) {
  if ( 6> strlen($comment_author_email) || '' == $comment_author )
    fail('Oopps,名字[Name]或邮箱[email]不对。');
  elseif ( !is_email($comment_author_email))
    fail('Oopps,邮箱地址[Email]不对。');
}
if ( '' == $comment_content )
  fail('是不是应该写点什么再提交?');
// Simple duplicate check
$dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND ( comment_author = '$comment_author' ";
if ( $comment_author_email ) $dupe .= "OR comment_author_email = '$comment_author_email' ";
$dupe .= ") AND comment_content = '$comment_content' LIMIT 1";
if ( $wpdb->get_var($dupe) ) {
  fail('评论重复了!有木有!');
}
$commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'user_ID');
if( !$user->ID ){
 $result_set = $wpdb->get_results("SELECT display_name, user_email FROM $wpdb->users WHERE display_name = '" . $comment_author . "' OR user_email = '" . $comment_author_email . "'");
 if ($result_set) {
 if ($result_set[0]->display_name == $comment_author){
 fail('博主你也敢冒充?');
 } else {
 fail('博主你也敢冒充?');
 }
 }
}
$comment_id = wp_new_comment( $commentdata );
$comment = get_comment($comment_id);
 
if( !$user->ID ){
 setcookie('comment_author_' . COOKIEHASH, $comment->comment_author, time() + 30000000, COOKIEPATH, COOKIE_DOMAIN);
 setcookie('comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + 30000000, COOKIEPATH, COOKIE_DOMAIN);
 setcookie('comment_author_url_' . COOKIEHASH, clean_url($comment->comment_author_url), time() + 30000000, COOKIEPATH, COOKIE_DOMAIN);
}
@header('Content-type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset'));
 xz_comment($comment, null);//这是我的调用评论函数,换成你的函数名。
 die();
}
}
add_action('init', 'ajax_comment');
Copy after login

Javascript code
Note: The following code requires Jquery framework support.
Add the following part to the javascript onload code.

if (jQuery('#commentform').length) {
  jQuery('#commentform').submit(function(){  
// 截获提交动作
//ID为 commentform 的表单提交时发生的函数,也就是整个留言输入框 form 的ID。
 var ajaxCommentsURL = window.location.href;
    jQuery.ajax({
      url: ajaxCommentsURL,
      data: jQuery('#commentform').serialize()+'&action=ajax_comment',  
      type: 'POST',
      beforeSend: function() {
        jQuery('#commenterror').hide();
        jQuery('#commentload').fadeIn();
      },
      error: function(request) {  //发生错误时
        jQuery('#commenterror').html(request.responseText);
        jQuery('#commentload').hide();  //隐藏 submit
        jQuery('#commenterror').fadeIn(); //显示 error 
      },
      success: function(data) {
        jQuery('textarea').each(function(){
          this.value='';
        });
        jQuery('#commenterror').fadeOut();
        if(jQuery(".commentlist li.comment").first().length != 0){jQuery(".commentlist li.comment").first().before(data)}  
        else {jQuery("ol.commentlist").append(data)}
        jQuery(".commentlist li.comment").first().hide(0,function(){$(this).slideDown(1000)});
        jQuery('#cmt-submit').attr('disabled', true).css({"background-color":"#6C6C6C","color":"#E0E0E0"});
        jQuery('#commentload').fadeOut(1600);
 setTimeout(function() {
        jQuery('#cmt-submit').removeAttr('disabled').css({"background-color":"#0086C5","color":"#FFFFFF"});
        },3000); 
      }
    });
    return false;
  } );
}
Copy after login

Note: The code still needs improvement. Because there is no time, it has not evolved further.

CSS code
Add css optionally.

#commentload,#commenterror{
 display: none;
 margin: 5px 0 0 0;
 color:#D29A04;
 float: left;
 font-size:16px;
 padding:0 0 0 20px;
}
#commentload{
 background: url("img/loading.gif") no-repeat bottom left ;
}
#commenterror{
 background: url("img/error.png") no-repeat bottom left ;
}
Copy after login

Principles and ideas
Principle:
Javascript submit data
php responds and outputs the results
Javascript gets the result and displays
Idea:
After clicking the submit button, Javascript intercepts the submission action
Intercept the submitted data (Name, Email, Web, Comment-text)
Use Javascript Jquery to simulate a browser submitting a POST (Name, Email, Web, Comment-text) request to WordPress
Construct a function to accept requests in the Function.php file, that is, the ajax_comment function in this column
If the request has no errors, the correct result will be output
If there is an error in the request, output the error result
Javascript to get correct results, dynamically added to the comment list
Javascript obtains error results and dynamically adds them to the submission prompt bar
Improvements
In terms of style, I really don’t have any sense of beauty, so I’m still learning.
The submit button should be grayed out and invalid for 3 seconds after it is clicked until the return result is obtained. This was not noticed before because I was testing on this machine and the submission was completed instantly. I discovered it during the remote test, but if I want to change it, I still have to change it. It needs to be tested. If the time is too tight, I won’t change it. I will improve it if I have the opportunity.

Summary
Because of the freedom and diversity of comment styles in WordPress themes, it seems that there has never been a universal AJAX comment plug-in,
Some experts can only publish their ideas and some common core codes while optimizing their blogs,
So if you want to implement some cool functions, you need an expert to help you,
Otherwise, you can only study code hard and hope that one day you can accumulate a lot of knowledge.
Please submit your own comments to verify the effect.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template