0

when user click for a second time click do not work, user need to reload the page again to it works

<script>
$(document).ready(function() {

  $("#like_post").click(function(e) {
     // $("#like_post").on("click", "#like_post", function (e) {
    e.preventDefault();


    var post_info = $("#post_info :input").serialize();
    $.post("backend/ajax/like_post.php", post_info).done(function(data) {
      $("#like_post").html(data);
     $("#like").load(location.href+" #like>*","");

    }).fail(function() {
      //alert("Error submitting forms!");
    })
  })
})
</script>

this is the backend return from db if user liked it will show

<div id="like_post><a href="" id="l"><input type="hidden" value="unlike" name="like_button" /><i style="color:red" class="fa fa-heart fa-2x" aria-hidden="true" data-toggle="tooltip" data-placement="top" title="'.$lang['you_liked_it'].'"></i>
    </a></div>

else it will show

 <div id="like_post"> <a href="" id="l"><input type="hidden" value="like" name="like_button" /><i class="fa fa-heart-o fa-2x" aria-hidden="true"  data-toggle="tooltip" data-placement="top" title="'.$lang['like_it'].'"></i>
</a></div>

the same validation is on frontend where is will change the hidden input to like, or unlike , my backend check is fine and returning all ok when I check the html response, but the problem is that jquery do not work when user like and unlike without reload the page, it just get the first click and after that user need to reload the page to it works.

I had a similar issue before and it was something with event delegation.

seven_seas
  • 703
  • 4
  • 21
  • Yes, use delegation. Since you are replacing the element with `.html()`, the event handler is no longer bound. – msg Aug 16 '19 at 01:04
  • could you explain me what should I change in my script? –  Aug 16 '19 at 01:04
  • 2
    Take a look [here](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements). I don't know your html, but `$("body").on('click', '#like_post', function(e) {` should do it. You can replace the `body` tag with whatever selector you want. – msg Aug 16 '19 at 01:07
  • cool, let me try –  Aug 16 '19 at 01:09
  • does it need to be `('click', or ("click",`? or id does not matter at all? –  Aug 16 '19 at 01:10

1 Answers1

0

Use the comment line in your code without "#like_post":

$("#like_post").on("click", function (e) {

});
hoangquyy
  • 1,893
  • 2
  • 14
  • 29