Javascript function doesn't work after adding content dynamically through ajax

I have a function

function reply(id) {
        $('#reply_'+id).toggle();
        return false;
    }

And Ajax function

<script type="text/javascript">
function post()
{
  var comment = document.getElementById("comment").value;
  var course_id = document.getElementById("course_id").value;
  var user_id = document.getElementById("user_id").value;
  if(comment)
  {
    $.ajax
    ({
      type: 'post',
      url: 'comments.php',
      data: 
      {
         comment:comment,
         course_id:course_id,
         user_id:user_id
      },
      success: function (response) 
      {
        document.getElementById("comment-list").innerHTML=response+document.getElementById("comment-list").innerHTML;
        document.getElementById("comment").value="";

      }
    });
  }

  return false;
}
</script>

And the content that is added after ajax call

...
...
 <p class="text-right"><a href="#" onclick="return reply(<?php echo $i; ?>);" class="btn btn-default btn-sm"><i class="fa fa-reply"></i> reply</a></p>    
...
...
<div class="row" id="reply_<?php echo $i; ?>" style="display: none;">
...
...

So basically that javascript functions toggle the div and it is working perfectly fine on page refresh but when adding through ajax success call the javascript toggle doesn't work. It will work after I refresh the page.

Anyway to fix this so toggle work when content added through ajax without refresh.

Thanks.

Answers 1

  • Change your content that is added after ajax call as below:

    <p class="text-right">
    <a href="#" data-id="<?php echo $i; ?>" class="btn btn-default btn-sm btnReply">
    <i class="fa fa-reply"></i> reply</a></p> 
    

    and write jquery code as below

    $("body").on("click", ".btnReply", function(event){
       var id =$(this).attr('data-id');
       reply(id);
    });   
    

Related Articles