0

I'm creating a forum and i want the comments to appear with their dates, this is the html:

<div id="forum" class="panel panel-default">
    <ul class="list-group">

    </ul>
</div>

I'm appending the elements with jquery:

$.ajax({
        url: '../public/comment',
        type: 'GET',
        dataType: 'json',
        success:function(response) {

            $('#forum ul').empty();
            for (var i in response['comments'])
            {
                $('#forum ul').append('<li class="list-group-item"> <ul> <li class="list-group-item">' +
                    response['comments'][i].date + '</li> <li class="list-group-item">' +
                    response['comments'][i].comment + '</li> </ul> </li> '); 
            }
        }
    });

But for every comment that i append to the forum the rest of the comments are duplicated and attached to it. If i have three comments it shows 7, if i have 4 it shows 15.

I realize that deleting the ul tags from the jquery solves the problem, but i need these tags for aesthetic reasons. what can be wrong?

Ruben Gonzalez
  • 143
  • 1
  • 15
  • Possible duplicate of [jQuery .append() duplicates content?](https://stackoverflow.com/questions/7249518/jquery-append-duplicates-content) – T.Todua Sep 12 '18 at 16:05

2 Answers2

1

I assume that every ajax call gets ALL comments for that matter. In that case simply replace the entire html of your list each time.

//clear your ul
$('#forum ul').html('');
//repopulate
$.ajax({
  url: '../public/comment',
  type: 'GET',
  dataType: 'json',
  success: function(response) {

    $('#forum ul').empty();
    for (var i in response['comments']) {
      $('#forum ul').append('<li class="list-group-item"> <ul> <li class="list-group-item">' +
        response['comments'][i].date + '</li> <li class="list-group-item">' +
        response['comments'][i].comment + '</li> </ul> </li> ');
    }
  }
});
kurt
  • 1,146
  • 1
  • 8
  • 18
  • I'm logging the result of the ajax call and everything is fine. anyway i was doing $('#forum ul').empty(); inside the success function. apparently is something with the ul tag – Ruben Gonzalez Sep 05 '15 at 15:24
1

By writing

$('#forum ul').append(...)

you append everything to every <ul> element within your #forum <div>, including the <ul> tags within your <li> tags.

Change it to

$('#forum>ul').append(...)

to select the immediate children only.

See this post also

Community
  • 1
  • 1
Olivier De Meulder
  • 2,493
  • 3
  • 25
  • 30