Implementation example of comments submission using AJAX technology in WordPress, wordpressajax

Source: Internet
Author: User

Implementation example of comments submission using AJAX technology in WordPress, wordpressajax

I have been interested in the Ajax Interaction Research of WordPress and have been very concerned about this technology. When talking about WordPress Ajax, I have to comment on Ajax submission, as a blog or forum comment, Ajax submission can not only improve user experience, but also greatly reduce server spending. After all, it is much easier to output a single comment to a new organization than to output a page. Although the current access volume has been relatively low, there is no server pressure problem, but I have always paid attention to user experience, of course, cannot give up such an opportunity to improve user experience. I took a leave of time this afternoon and submitted the Ajax comments on this topic for preliminary completion.

Let's get started with the Code: (the principles and ideas are at the end)
You can adjust the following code based on the structure of your topic.

WordPress Ajax submits comments to PHP code
Add the following content to the topic function. php file.

// Most of the following code comes from yinheli. This Code helps you eliminate some errors and streamline the code below. // The yinheli blog does not work, so the link is not provided here. // Edited by XiangZi DEC.17TH 2011 function fail ($ s) {// header of the virtual Error header ('HTTP/1.0 500 Internal Server error'); echo $ s; exit ;} function ajax_post_comment_slow () {fail ('Needless to say it's so fast? Let's talk about it! ');} // The comment is too fast to output the code. Add_filter ('comment _ flood_trigger ', 'ajax _ post_comment_slow', 0); // hook function ajax_comment () of the returned content when a comment is sent too quickly () {// Ajax php response code if ($ _ POST ['action'] = 'ajax _ comment') {global $ wpdb, $ db_check; // Check DB if (! $ Wpdb-> dbh) {echo ('ur 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 determines the wp source code that looks like a copy. For details, see include/comment. php do_action ('comment _ id_not_found ', $ comment_post_ID); fail ('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 ('com Ment_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 ['mail']); $ 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 ($ u Ser-> 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? Registered? ') ;}$ Comment_type = ''; if (get_option ('require _ name_email ')&&! $ User-> ID) {if (6> strlen ($ comment_author_email) | ''= $ comment_author) fail ('oopps, the Name [Name] or email address [email] is incorrect. '); Elseif (! Is_email ($ comment_author_email) fail ('opps, the Email address [Email] is incorrect. ');} If (''= $ comment_content) fail (' Should I write something before submitting? '); // 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 ('Repeat the comment! Yes! ');} $ 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 ('Do you dare to impersonate a blogger? ');} Else {fail ('Do you dare to pretend to be a blogger? ') ;}}$ 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 ('Con Tent-type :'. get_option ('html _ type '). '; charset = '. get_option ('blog _ charset'); xz_comment ($ comment, null); // This Is My function for calling the comment function. Change it to your function name. Die () ;}} add_action ('init ', 'ajax _ comment ');

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

If (jQuery ('# commentform '). length) {jQuery ('# commentform '). submit (function () {// intercept the submission action // the function that occurs when the form with the ID of commentform is submitted, that is, the ID of the form in the entire message input box. 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('your commenterror'{.html (request. responseText); jQuery ('# commentload '). hide (); // hide submit jQuery ('# commenter Ror '). fadeIn (); // Display 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 ', true0000.css ({"background-color": "# 6C6C6C", "color": "# E0E0E0"}); jQuery (' # commentload '). fadeOut (1600); setTimeout (function () {background ({"background-color": "#0086C5", "color": "# FFFFFF "});}, 3000) ;}}); return false ;});}

Note: there is still a need for code improvement, because there is no time, so there is no further evolution.

CSS code
Add css randomly.

#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 data submission
Php response and output results
Javascript returns and displays
Ideas:
After you click the submit button, Javascript intercepts the submission action.
Intercepted data (Name, Email, Web, and Comment-text)
Using Javascript Jquery to simulate a browser to submit POST (Name, Email, Web, Comment-text) requests to WordPress
The Function. php file constructs a request-receiving Function, that is, the ajax_comment Function in this column.
If no error is returned, the correct result is output.
If an error occurs in the request, an error is returned.
Javascript gets the correct result and dynamically adds it to the comment list.
Javascript gets the error result and dynamically adds it to the submission prompt bar.
Improvement
Style, I do not have any aesthetic, so I am learning.
The submit button should be grayed out three seconds after it is clicked to get the returned result. It was not noticed that the submission was completed in an instant due to local testing, we found it during the remote test, but we still need to test it if we want to change it. If it is too short, we will not change it. We have the opportunity to improve it.

Summary
Because of the freedom and diversity of comment styles in WordPress Themes, it seems that there is no universal AJAX comment plug-in so far,
Some experts can only announce their ideas and some general core code while optimizing their blogs,
So if you want to implement some cool functions, or someone else will help you,
Otherwise, you can only learn the code well and look forward to accumulating Some details one day.
For the effect, please submit your own comments for verification.

Articles you may be interested in:
  • Optimize time display of articles and comments in WordPress
  • Using AJAX to asynchronously retrieve comments to user portraits in WordPress
  • Detailed description of PHP functions that call comment templates and output comments cyclically in WordPress
  • WordPress restricts non-administrator users to comment only once after the article
  • Describes the PHP functions used in WordPress to obtain comment templates and search forms.
  • Solve the problem that WordPress cannot comment after using CDN
  • Use jQuery to implement @ ID floating display of comments in WordPress
  • Compile a PHP script to implement the comment paging function in WordPress
  • Example of modifying the PHP script to enable WordPress to intercept spam comments
  • Customize the default comment Avatar and delay loading in WordPress
  • Some methods to optimize guest comment in WordPress
  • Display and hide comments and reference Buttons over the mouse in WordPress

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.