What is the best way to update comments after submitting an AJAX request?

I stumbled upon a lightweight script that allows for submitting WordPress comments via AJAX. Although the comments are successfully submitted, the new comment does not appear immediately; only the comment count gets updated. Upon manually refreshing the page, the new comment is displayed. Here's the code snippet:

jQuery(document).ready(function($){
  jQuery.noConflict();
/* the acp_long is removed here. it got printed in page head by php
   acp_lang[]:
   [0]: 'Loading...'
   [1]: 'Please enter your name.'
   [2]: 'Please enter your email address.'
   [3]: 'Please enter a valid email address.'
   [4]: 'Please enter your comment'
   [5]: 'Your comment has been added.'
   [6]: 'ACP error!'
*/
// initialise
var form, err, reply;
function acp_initialise() {
  jQuery('#commentform').after('<div id="error"></div>');
  jQuery('#submit').after('<img src="'+acp_path+'loading.gif" id="loading" alt="'+acp_lang[0]+'" />');
  jQuery('#loading').hide();
  form = jQuery('#commentform');
  err = jQuery('#error');
  reply = false;
}
acp_initialise();

jQuery('.comment-reply-link').live('click', function() {
  // checks if it's a reply to a comment
  reply = jQuery(this).parents('.depth-1').attr('id');
  err.empty();
});

jQuery('#cancel-comment-reply-link').live('click', function() {
  reply = false;
});  

jQuery('#commentform').live('submit', function(evt) {

  err.empty();

if(form.find('#author')[0]) {
  // if not logged in, validate name and email
  if(form.find('#author').val() == '') {
  err.html('<span class="error">'+acp_lang[1]+'</span>');
  return false;
  }
  if(form.find('#email').val() == '') {
  err.html('<span class="error">'+acp_lang[2]+'</span>');
  return false;
  }
  var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  if(!filter.test(form.find('#email').val())) {
  err.html('<span class="error">'+acp_lang[3]+'</span>');
  if (evt.preventDefault) {evt.preventDefault();}
  return false;
  }
} // end if

if(form.find('#comment').val() == '') {
  err.html('<span class="error">'+acp_lang[4]+'</span>');
  return false;
}

jQuery(this).ajaxSubmit({

  beforeSubmit: function() {
  jQuery('#loading').show();
  jQuery('#submit').attr('disabled','disabled');
  }, // end beforeSubmit

  error: function(request){
  err.empty();
  var data = request.responseText.match(/<p>(.*)<\/p>/);
  err.html('<span class="error">'+ data[1] +'</span>');
  jQuery('#loading').hide();
  jQuery('#submit').removeAttr("disabled");
  return false;
  }, // end error()

  success: function(data) {
  try {
  // if the comments is a reply, replace the parent comment's div with it
  // if not, append the new comment at the bottom
  var response = jQuery("<ol>").html(data);
  if(reply != false) {
  jQuery('#'+reply).replaceWith(response.find('#'+reply));
  jQuery('.commentlist').after(response.find('#respond'));
  acp_initialise();

  } else {//  
  if (jQuery(document).find('.commentlist')[0]) {
  //console.log("find it"); this log line shows it finds the place to append things
  response.find('.commentlist li:last')..hide().appendTo(jQuery('.commentlist')).slideDown('slow');
  } else {
  jQuery('#respond').before(response.find('.commentlist'));
  }
  if (jQuery(document).find('#comments')[0]) {
  jQuery('#comments').html(response.find('#comments'));
  } else {
  jQuery('.commentlist').before(response.find('#comments'));
  }
  }
  form.find('#comment').val('');
  err.html('<span class="success">'+acp_lang[5]+'</span>');
  jQuery('#submit').removeAttr("disabled");
  jQuery('#loading').hide();

  } catch (e) {
  jQuery('#loading').hide();
  jQuery('#submit').removeAttr("disabled");
  alert(acp_lang[6]+'\n\n'+e);
  } // end try

  } // end success()

  }); // end ajaxSubmit()

  return false; 

}); // end form.submit()

}); // end document.ready()

Is there any clue within the provided code that might be causing the issue of the new comment not appearing?

Update:

After receiving help from HMR in the chatroom, we conducted tests using Firebug. The outcome was as follows:

response.find('.commentlist li:last')
Successfully identifies the recently posted reply
jQuery('.commentlist')
Refers to an existing visible <div> element on the page; however, when trying to add the new comment to this <div> using:
response.find('.commentlist li:last').appendTo(jQuery('.commentlist'));
The newly added comment does not display.

We express our gratitude to HMR for their assistance, but due to a typo error made by me and the need for file cleanup, our testing had to be halted.

Why is the append operation not functioning properly when adding the HTML content from the ".commentlist" element? It has been demonstrated that it works when the element is empty, so there may be something specific about the existing HTML preventing newly added comments from showing up.

Answer №1

If the final message displayed in the console is "find it," would you be able to provide additional data for that section?

} else {
   if (jQuery(document).find('.commentlist')[0]) {
       console.log("find it");
       console.log("verification:",response.find('.commentlistli:last'));
       console.log("appending to:",jQuery('.commentlist'));

Answer №2

To ensure your feedback is displayed correctly, enclose it within an HTML tag with the attribute class="commentlist". The code snippet

jQuery('.commentlist').after(response.find('#respond'));
attempts to place the new comment in the specified location. If this designated element does not exist, the operation will fail.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

locate the following div using an accordion view

Progress: https://jsfiddle.net/zigzag/jstuq9ok/4/ There are various methods to achieve this, but one approach is by using a CSS class called sub to hide a 'nested' div and then using jQuery to toggle the Glyphicon while displaying the 'nest ...

What is causing the router.events to not fire for FooComponent in my Angular project?

Upon opening the following link , the eventsFromFoo entries in the console are nowhere to be found. It appears that this.router.events is failing to trigger for FooComponent. Any insights on why this might be happening? I am in urgent need of capturing t ...

Set up specific vue.config.js configurations for unique environments in Vue

I am working on a multi-page app where I want certain pages to only show up in my development environment. Here's how my vue.config.js looks: module.exports = { productionSourceMap: false, pages: { index: "src/main.js", admin: { ...

When I followed the instructions in section 3.1 and pasted the PHP text into a new file called service.php, I encountered an issue where nothing appeared when I attempted to run the file at http://mydomain/service

While following this tutorial, I encountered an issue with my Bluehost hosting service and WordPress. Can anyone help me understand why I am receiving an error message when entering the URL? <?php // Establish connection $con=mysqli_connect("loc ...

Should data validations be implemented on both the client-side and server-side for optimal security and accuracy?

My query is related to utilizing Angular on the client side and Laravel API on the server side. I'm wondering if it is more effective to implement data validations on both ends. ...

Tips for getting FormData() to function on Internet Explorer browsers

Is there a way to get this code working on Internet Explorer? I am having trouble with the FormData() API not being supported by IE browsers. Are there any alternative APIs that can be used in place of new FormData() for IE? var fd = new FormData(); fd. ...

How to disable the ripple effect of a parent button in Material UI when clicking on a nested child button?

Attempting to nest one button within another (IconButton inside ListItem with the button prop) is proving challenging. The issue lies in the fact that the ripple animation of the ListItem is triggered even when clicking on the IconButton. Ideally, I would ...

Most efficient method for revealing all concealed divs using JavaScript

I have a large div containing multiple hidden divs that can be displayed individually or all at once. Here is an example of how it's structured: <div class="maindiv"> Print "<a href=javascript:show()>Click here to show all</a> ...

Switching over to WordPress - A new MySQL GUID column journey

Currently, I am facing a minor issue with a WordPress migration process. To expedite the procedure, I bulk uploaded posts from csv on my local WAMP server and then uploaded/imported a SQL dump to the remote server. Within the guid column of the wp_posts t ...

Laravel: Input information into a form containing multiple dropdown menus

I am in search of a Laravel or HTML example that demonstrates filling out a form with multiple drop-down lists. Here's my scenario: I have the following text inputs: name_customer, phone_customer, email_customer. I want the form fields to automatical ...

Differences between visibility property manipulation in HTML and JS

One issue I am facing is that when I add a hidden property to a button in the HTML, it remains invisible. <button id="proceed_to_next_question" hidden> Next Question </button> However, if I remove the hidden property and include the following ...

Transmit a JSON object to the server using a JavaScript function

I am attempting to transmit a JSON object to a remote server but I am not receiving a success message. Can someone please help me identify what is incorrect in this code: function sendSMS(){ var input = '{"header":"****","****":*****,"****":"**** ...

Tips for implementing event.preventDefault() with functions that require arguments

Here is a code snippet that I'm working with: const upListCandy = (candy) => { /* How can I add event.preventDefault() to make it work properly? */ axios.post("example.com", { candyName: candy.name }).then().ca ...

Retrieve information from various tables in a SQLite database using Node.js

Is there a method to retrieve all data from multiple tables in a database? Currently, I have managed to fetch all data from a single table: router.get('/', function (req, res, next) { db.serialize(function () { db.all('SELECT id, name ...

Choose all the alternative A radio buttons utilizing JavaScript

If the "4 stars" option is selected at the top, I want all corresponding "4 stars" options in the form to be automatically selected. Similarly, if "3 stars" is chosen, I need all the "3 stars" options to be selected. I attempted to achieve this functionali ...

A guide on invoking a JavaScript function after receiving a response from an AJAX request

I am facing an issue with a $.POST call that returns the name of a function to be executed, however, the function is not being triggered and I'm unsure why. Below is an example: JavaScript file snippet: $(function(){ $.post('test.php&apos ...

Error: JSON syntax unexpectedly found token 'u'

Utilizing a YUI function, I am attempting to retrieve a status message from a PHP function that provides the correct status in JSON format. Upon triggering the event, an error message is displayed: "Syntax error unexpected token u" The source code is as ...

What is the process of using TypeScript to import a constant exported in JavaScript?

In the environment I'm using typescript 2.6.1. Within react-table's index.js file, there is a declaration that looks like this: import defaultProps from './defaultProps' import propTypes from './propTypes' export const React ...

Tips for preventing text from breaking onto a new line in Safari

I have cforms plugin installed on a WordPress page. Interestingly, the word "required" in Russian appears to consist of two words as per the translation office. While it displays correctly in Firefox, in Safari it breaks and aligns to the bottom left of ...

React custom slider component is failing to meet expectations

I've been working on enhancing my React skills and building my portfolio. Instead of using a library, I opted to create a custom slider using the code below: const ProjectWrapper = styled.div` .container { transform: translateX(-$ ...