The implementation example of using AJAX technology to submit comments in WordPress _javascript tips

Source: Internet
Author: User
Tags setcookie

has been interested in WordPress Ajax Interactive Research, and has been very concerned about the technology, the WordPress Ajax will have to talk about the comments Ajax submission, as a blog, forum comments Ajax submission can not only improve the user experience, but also can significantly reduce server expenditure , after all, it is much simpler to output a single comment than to rearrange the output of a page. Although the amount of traffic has been relatively low, there is no problem with server pressure, but always pay attention to the user experience of me, of course, can not give up such an opportunity to enhance the user experience. Today I smoked for an afternoon and submitted the Ajax comments on this topic to the preliminary completion.

Straight to the point, directly on the code: (Principle and ideas in the end)
According to their own theme of different structures, the following code please adjust yourself.

WordPress Ajax Submit Comments PHP Code
Add the following section to the subject function.php file.

Most of the following code is derived from Yinheli through this part of the Code, the elimination of partial errors, optimization and streamlining of the following code.
Yinheli Blog does not do, so here is not to the link.
  Edited by Xiangzi dec.17th function fail ($s) {//Virtual Error Header part header (' http/1.0 Internal Server Error ');
  Echo $s;
Exit } function Ajax_post_comment_slow () {fail (' not to mention so fast? Think it over!
');
//Comments too fast output code.
Add_filter (' Comment_flood_trigger ', ' Ajax_post_comment_slow ', 0); Hang a comment too quickly, return the contents of the hook function ajax_comment () {//Ajax PHP Response part of the code 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)) {//This set of judging seemingly copied WP source code.
  See: Include/comment.php do_action (' Comment_id_not_found ', $comment _post_id); Fail (' The post you are trying to comment on does is not currentlyDatabase. ');
  } 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 (' Martian?
Register a? ');
} $comment _type = '; if (get_option (' Require_name_email ') &&! $user->id) {if (6> strlen ($comment _author_email) | | "= = = $comment _author) fail (' Oopps, name or email [email] not.
  '); ElseIf (!is_email ($comment _author_email)) fail (' Oopps, email address [email] is wrong.
'); if (' = = $comment _content ') fail (' Should I write something before submitting it?
'); Simple duplicate Check $dupe = "Select comment_id from $wpdb->comments WHERE comment_post_id = ' $comment _post_id '
D (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 (' comments repeated! There are wood! ');} $commentdata = Compact (' comment_post_id ', ' comment_author ', ' com Ment_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 disp Lay_name = ' ". $comment _author. "' OR user_email = '". $comment _author_email.
 "'"); if ($result _set) {if ($result _set[0]->display_name = = $comment _author) {fail you dare to impersonate?
 '); else {fail (' Bo Lord, you dare to pretend?
 ');
}} $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);//This is my call comment function, replaced by your function name.
Die ();
 } add_action (' init ', ' ajax_comment ');

Javascript Code
Note: The following code requires the Jquery framework support. The
JavaScript onload code adds the following sections.

if (jquery (' #commentform '). Length) {jquery (' #commentform '). Submit (function () {//intercept a letter that occurs when submitting an action//id for a commentform form submission
 Number, which is the ID of the entire Message input box form.
    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 ') when an error occurs. html (request.responsetext);  JQuery (' #commentload '). Hide (); Hide Submit jQuery (' #commenterror '). FadeIn ();
        Show Error}, Success:function (data) {jQuery (' textarea '). each (function () {this.value= ';
        });
        JQuery (' #commenterror '). fadeout ();  
        if (jquery (". Commentlist li.comment"). Length!= 0) {jquery (". Commentlist li.comment").-A (). before (data)} else {jQuery ("Ol.commentlist"). Append (DatA)} jQuery (". Commentlist li.comment").-A (). 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: There is still a need to improve the code, because there is no time, so there is no further evolution.

CSS Code
CSS Optional part added.

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

Principle, thinking
principle:
Javascript Submit Data
PHP Response and output results
Javascript gets results and displays
Ideas:
After clicking the Submit button, Javascript intercepts the submit action
Intercept submitted data (Name, Email, Web, Comment-text)
Use Javascript Jquery Simulation browser to submit post (Name, Email, Web, comment-text) request WordPress
In the function.php file, you construct a function that accepts the request, that is, the Ajax_comment function in this column
If the request has no errors, output the correct result
If the request has an error, the output error result
Javascript gets the correct results and dynamically adds to the comments list
Javascript gets error results, dynamically adds to submit prompt bar
improved
in terms of style, I do not have any aesthetic feeling, so I am studying.
The submit button should be grayed out for 3 seconds after clicking to get the return result. This point before because in the native test, the submission of instantaneous completion did not notice, remote testing time found, but to change the words to be tested, too tight time will not change, there is a chance to improve.

Summarize
because the WordPress theme of the freedom of comment style, diversity, so it seems that there has been no universal Ajax Comment Plug-ins,
Some experts can only optimize their blog, the idea and some of the Common Core code to do the announcement,
So to achieve some cool features or someone to help you,
Or you can only learn the code well, look forward to a day to be able to accumulate thin hair.
Effect please submit your own comment validation.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.