search
HomeWeb Front-endJS TutorialImplementation example of using AJAX technology to submit comments in WordPress_javascript skills

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');

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;
  } );
}

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 ;
}

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.

Statement
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
wordpress后台乱码怎么办wordpress后台乱码怎么办Feb 03, 2023 pm 01:48 PM

wordpress后台乱码的解决办法:1、在wordpress的“wp-admin”文件夹下找到“admin.header.php”文件;2、将“charset”属性值设置为“UTF-8”格式即可恢复正常。

如何解决wordpress标签错误问题如何解决wordpress标签错误问题Feb 03, 2023 pm 02:03 PM

wordpress标签错误的解决办法:1、找到并打开wordpress的“wp-includes”目录下的“class-wp.php”文件;2、修改内容为“$pathinfo = isset( $_SERVER['PATH_INFO'] )?mb_convert_encoding($_SERVER['PATH_INFO'],'utf-8','GBK') : '';”即可。

WordPress设置独立的Description和KeywordsWordPress设置独立的Description和KeywordsFeb 21, 2023 am 11:14 AM

你下载的WordPress主题提供的keywords和description这两个meta标签一般都做得很差,或者根本就不提供,这样不利于SEO。本文将指导你如何给主页、分类、页面以及文章页添加单独的Description 和 Keywords。

wordpress乱码怎么办wordpress乱码怎么办Mar 09, 2023 am 09:13 AM

wordpress乱码的解决办法:1、修改“wp-config.php”文件里的“define(’DB_CHARSET’, ‘utf8′);”为“define(’DB_CHARSET’, ”);”;2、把新数据库的编码设置成“latin1_swedish_ci”;3、以uft8的格式导入备份的数据库文件即可。

wordpress进不去怎么办wordpress进不去怎么办Feb 23, 2023 am 09:41 AM

wordpress进不去的解决办法:1、把地址栏“wp-login.php”后面的参数删掉,然后重新输入密码登录;2、登录FTP,下载“pluggable.php”文件,然后找到“ADMIN_COOKIE_PATH”并将它替换为“SITECOOKIEPATH”即可。

wordpress是saas吗wordpress是saas吗Feb 21, 2023 am 10:40 AM

wordpress不是saas。SaaS是一种软件销售模式,它主要针对云端应用软件,而WordPress是一款CMS系统,它主要针对网站构建和管理。虽然WordPress可以作为SaaS提供服务,但它本质上不是一种SaaS应用。

2023年最新WordPress视频教程推荐2023年最新WordPress视频教程推荐Oct 25, 2019 pm 01:12 PM

本次PHP中文网整合了相关的视频教程,中文手册,以及相关的精选文章安利给大家,统统免费!!!通过我们分享的视频,可随时随地免费观看教程视频,也不需要迅雷或者百度网盘下载了。

wordpress是哪一年的wordpress是哪一年的Feb 01, 2023 am 10:26 AM

wordpress是2003年发布的;Matt于2003年5月27日宣布推出第一版WordPress,受到了社区的欢迎,它基于b2 Cafelog并有显著改进;WordPress的第一个版本包括全新的管理界面、模板、XHTML 1.1兼容模板、内容编辑器。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function