CSS selectors following an ajax request (commenting system)

Issue:

After submitting a comment on a webpage, the comments are not displaying correctly. I want them to slide down below the last added comment. It seems to be related to CSS selectors. Can someone help me figure out which selector I need to use?

Any assistance would be greatly appreciated. Thank you!

$(function() {
  "use strict";
  var commentsform = $('#commentsForm');
  var errorTemplate = '<div class="alert alert-danger"><span class="glyphicon glyphicon-warning-sign"></span>&nbsp;{error}</div>';
  var successTemplate = '<div class="alert alert-success"><span class="glyphicon glyphicon-warning-sign"></span>&nbsp;{error}</div>';
  var commentsTemplate = '<div class="row" id="comments"><div class="col-md-2 col-sm-2 hidden-xs"><figure class="thumbnail">{photo}<figcaption class="text-center">{username}</figcaption></figure></div><div class="col-md-10 col-sm-10"><div class="panel panel-default arrow left"><div class="panel-body"><header class="text-left"><div class="comment-user"><i class="fa fa-user"></i> {username}</div><time class="comment-date"datetime="{date}"><i class="fa fa-clock-o"></i> {date}</time></header><div class="comment-post">{comment}</div></div></div></div></div>';
  var messages = $('#messages');
  var comments = $(''); //which one selector do I have to type for it?

  commentsform.submit(function() {
    $.ajax({
      dataType: "json",
      url: '/users/ajax/add-comments/',
      type: 'POST',
      data: commentsform.serialize(),
      success: function(response) {
        if (response) {

          if (response.errors) {
            errorTemplate = errorTemplate.replace(/\{error\}/, response.msg);
            messages.show();
            messages.html(errorTemplate);
            setTimeout(function() {
              messages.slideUp(1500);
            }, 1000);
            return false;
          } else {
            $('#commentsForm')[0].reset();
            var comment = commentsTemplate;
            successTemplate = successTemplate.replace(/\{error\}/, response.msg);
            messages.show();
            messages.html(successTemplate);
            setTimeout(function() {
              messages.slideUp(1500);
            }, 1000);

            comment = comment.replace(/\{photo\}/, response.avatar);
            comment = comment.replace(/\{username\}/, response.username);
            comment = comment.replace(/\{comment\}/, response.comment);
            comment = comment.replace(/\{date\}/, response.date);
            comments.append(comment);
            comments.find('#comments ::after').slideDown();
          }

        }
      }
    });
    return false;
  });

});
<section class="comment-list">
  <div class="row comments">
    <div class="col-md-10 col-sm-10">
      <div class="panel panel-default arrow left">
        <div class="panel-body">
          <header class="text-left">
            <div class="comment-user">
              <i class="fa fa-user"></i>
            </div>
            <time class="comment-date" datetime="">
              <i class="fa fa-clock-o"></i> 
            </time>
          </header>
          <div class="comment-post"></div>

        </div>
      </div>
    </div>
  </div>
</section>

I'm struggling with this issue and don't know how to fix it!

Answer №1

To add any of the following as the final statement in the success callback of ajax:

Utilize last()

$('.comments').last().slideDown();

OR

You also have the option to utilize :last pseudo-selector:

$('.comments:last').slideDown();

Both options will target the last element with the class comments

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

When Rails renders a hash that contains Float::NAN objects, it may result in invalid JSON being

When returning JSON for a Rails controller call, I encountered an issue with NaN objects in the Ruby hash causing errors in the browser: { "value": NaN } Error: Parse error on line 1: "value": NaN Upon further research, I found that NaN is not a va ...

the mobile website is not properly aligned on a horizontal axis

As I work on creating a mobile version of my website, I've come across a challenge: The entire site fits perfectly on the computer at a browser width of 480px, but when viewed on my mobile phone (regardless of the browser used), it leaves space on the ...

Tips for beginning the process of creating a website's user interface

After initially developing my system without any styling, including bootstrap and CSS, I now find myself needing to add them. While I have reviewed the concepts on W3Schools and have a basic understanding, I am struggling with the sequence of implementat ...

Unable to display the outside table border in CSS styling

Lately, I've been relying on 'border = 1' in my HTML for styling, but I've come to the realization that using CSS would be more efficient. So, I went ahead and created a simple border class like this... .basicborder table, .basicborder ...

Is it possible to keep the vertical scrollbar always visible in jqGrid?

In my application, I have multiple jqGrids that may or may not have enough rows to need a vertical scrollbar initially. However, new rows can be added dynamically to these grids, eventually requiring a scrollbar. The issue arises when a grid does not have ...

Locate and substitute text, language equivalency

I'm encountering issues with finding and replacing words in PHP files, especially when dealing with a large number of them. I'm considering using javascript/jQuery as an alternative solution. I want to create a table mapping word_to_replace to ne ...

Optimizing the Placement of Dynamic Google Maps

After setting up a responsive Google map using this jsFiddle and guidance from this stack overflow post, I encountered an issue. How can I keep the map centered on the marker across various viewports and browser sizes? I came across a solution in this res ...

The node.js and express.js update operation (CRUD) is not rendering the CSS files properly

I am currently developing a CRUD app using Node.js/Express.js with EJS as the templating engine. The concept I'm working on involves displaying user_ids from a database, and when an admin clicks on a user_id, it should redirect them to the edit_team. ...

Retrieve the URL of a particular XML document from the server using a PHP script, then dynamically load it into a JavaScript file for further processing

As I work on my website, users have the ability to upload and download files while I generate an XML log with operation details. One page on the site displays a table created by reading this XML log. Everything functioned properly when it was all stored l ...

Sending Laravel validation errors back to an Ajax request

Need help with passing validation errors back to my ajax call in order to stop the page from progressing and show those errors to the user. /* * Creating a new user after completing the initial part of the form. * */ public function createUserAndOrder(R ...

Access the checkboxes that were previously selected and store them for future use when the page is

I am working on an HTML code where checkboxes are automatically checked and upon clicking a button, the values of checkboxes are passed through a function. Additionally, when a user checks a checkbox, the corresponding children checkboxes are also checked. ...

Display email address in a concise manner

Managing user information in my project involves capturing both username and email address. While the username is optional, the email address is mandatory with a maximum length of 100 characters. My issue arises when the email address exceeds 60 character ...

Creating a private variable to perform a select_sum query

I have defined private variables in my CodeIgniter code like this: private $table = 'phone'; private $column_order = array(null, 'name', 'price'); private $type = array('type'); private $battery_consumption = array ...

Issues with jQuery AJAX, occasionally experiencing repeated requests

Currently, I am in the final stages of revamping our JavaScript system by transitioning from Prototype to jQuery. We have numerous AJAX requests that are triggered when specific events occur on certain elements. One instance of this is when a new event is ...

Attempting to toggle the visibility of div elements through user interaction

I'm having an issue with click events on several elements. Each element's click event is supposed to reveal a specific div related to it, but the hidden divs are not appearing when I click on the elements. Any help in figuring out what might be g ...

Presenting XML data in HTML using a customized CSS stylesheet

I've explored various methods for showcasing an XML file on a web page using HTML, but I haven't yet encountered one that incorporates a CSS style sheet. The XML file I have already includes a CSS style sheet. When viewed in a web browser, the . ...

Retrieve data from a function in PHP while being outside of it

Embarking on this new journey of creating a plugin in wordpress, I find myself faced with the task of integrating jQuery code into my footer. The function at the beginning of my document serves this purpose, and here is a simplified version: function slug ...

Looking to properly display data using PHP, MySQL, and Ajax? Check out this helpful guide with step-by-step instructions on

This question involves using multiple languages to complete a webpage. You can find the URL to the page here. Currently, I only have an outline of the page and hope to utilize PHP, MySQL, and AJAX to finalize it. Can you guide me on how to set up the dat ...

The checkbox tab index fails to function properly when set to hidden with a custom design

I have implemented a custom design for a checkbox using CSS. label { position: relative; margin-bottom: 0.5em; } .input-field { width: 100%; border: 1px solid #ecf0f1; padding: 0.5em; } input[type="radio"], input[type="checkbox"] { display: ...

Personalized designing of each letter

Is there a way to style numbers without using something like <span></span>? I'm looking for a clean way to do this for each sign. Attached is an example showing a "flip clock" effect that I would like to achieve. I have come across plugi ...