Skip to content
Advertisement

How to display show replies button for the comment which has replies?

I am creating nested comment system with reply. comments goes longer and longer in page that is why I wanted to toggle replies.

I already do that auto adding class margins etc.

I have problem with displaying button, show replies button displays under all comments which has parent-id 0, even if it doesn’t have the replies.

because of this :

JavaScript

Which is working correct way for the class and margin etc.

Here is the php code :

JavaScript

Database setup : enter image description here

Solved I used multilevel recursive function (Like a multilevel menu) it works fine.

Advertisement

Answer

First of all I’ve saw few mistakes in your code:

  • Your code makes too many requests to your database – for each comment you will make a new request your database to get it’s sub comments – soon this will cause slow load speed of your pages
  • Your database structure doesn’t use indexes – with many records this will cause slow requests to this table
  • Your html code is not good

Database structure for my example:

JavaScript

PHP Code to generate the html:

JavaScript

As you can see in my example I’m getting all comments at once and after that I’ve made few things:

  • Getting the comments as associative array with comment_id as key in getArrayWithKeys function
  • Getting a nested associative array with parent comments and all of their sub comments are in comments key of the array in buildNestedComments function
  • Getting the html for all of these comments where sub comments are nested in div with class sub-comments for easier management with javascript

Then you will be able to use a little css and javascript to style this html and to show/hide sub comments.

Also you have to think about few points:

  • Amount of comments – if there are a lot of comments maybe it will be better to load first 10-20 comments
  • Lazy load of comments – first load all parent comments and then load their sub comments
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement