sooraj subramanyan sooraj subramanyan -4 years ago 87
Javascript Question

how to display ajax response to a <div> inside a for loop

I am trying to edit comment box, so there are many users to comment to a post. Each user can edit their comments. The comments are fetched from database and for each the comments written to a

<div class="view-comment">
.

My issues is that the single edit result displays in all comment fields. I think it's because of the code inside a loop. How can I change them separately?

<?php foreach ($comments as $row)
{
$comment = $row["comment"];
$username = $row["username"]; ?>

<div class="view-coment" ">
<div class="comment-padd">
<div class="comments">
<div class="row">
<div class="col-md-1">
<div class="coment-lft">
<?php if($comment) { ?>
<img src="<?php echo base_url() ?>img/avatar/<?php echo $username ;?>.jpg" class="img-response">
</div>
</div>
<div class="col-md-11">
<h2><?php echo $row['username'];?></h2>
<p><?php echo $row['comment'];?></p>
<hr>
</div>
<?php } ?>
</div>
<?php if ($username == $this->session->userdata('username') ){ ?>
<div class="comments-edit">
<div class="dropdown">
<a class=" dropdown-toggle" id="cmnt"><i class="fa fa-angle-down " aria-hidden="true" data-toggle="dropdown"></i></a>
<ul class="dropdown-menu-5" aria-labelledby="cmnt">
<input type="button" id="edit" value="Edit" />
<button class="my_button" id="<?php echo $row['id']; ?>" >edit</button>


$('button.my_button').click(function(e) {
e.preventDefault();
var url = $(this).attr('data-url');
var id = $(this).attr('id');
// alert(id);

$.ajax({
type: "POST",
url: '<?php echo site_url('home/comment_edit'); ?>',
data: 'id=' + id,
cache: false,
success: function(data){
$('.view-coment').html(data);
}
});
return false;
});

Answer Source

@sooraj subramanyan as menstion by @Rory McCrossan please correct your html first. Then you can make your comment box unique as follow.

<div class="view-coment" id="comment_<?php echo $row['id']; ?>">

and in your js update the comment box with this

$('#comment_'+id).html(data);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download