JQuery Ajax: Total Likes not updating for post when pressing Like button

只谈情不闲聊 提交于 2021-02-11 15:38:36

问题


Two JQuery Ajax calls. First brings back user messages from MySQL, the number of likes for that message and a button for the user to like the message. This request is working.

Second Ajax request to fire from the user pressing the like button created from the first Ajax request. However, nothing appears to happen on pressing the button (no errors). Tried to view the results as an alert or in the console but nothing happened.

Ajax request 1:

dataType: 'json',
success: function(response) {

  $.each(response, function() {
      $.each($(this), function(i, item) {
      var mycss = (item.Type == 1) ? ' style="color: #ffa449;"' :'';
      $( '.content' ).append( '<div class="post"><div class="post-text"> ' +item.MessageText+ ' </div><div class="post-action"><input type="button" value="Like" id="like_'+item.ID+'_'+item.UserID+'" class="like" '+mycss+' /><span id="likes_'+item.ID+'_'+item.UserID+'">'+item.cntLikes+'</span></div></div>');

      });
  });
}

Example of the html produced:

<div class="post"><div class="post-text"> This is message example text. </div><div class="post-action"><input type="button" value="Like" id="like_1_f6khb11ldm2hek6bvs3qd2oef6" class="like"><span id="likes_1_f6khb11ldm2hek6bvs3qd2oef6">12</span></div></div>

Ajax request 2:

dataType: 'json',
success: function(data){
    var likes = data['likes'];
    var type = data['type'];

    $("#likes_" + postid + "_" + userid).text(likes);
    if(type == 1){
        $("#like_" + postid + "_" + userid).css("color","lightseagreen");
    }
    if(type == 0){
        $("#like_" + postid + "_" + userid).css("color","#ffa449"); 
    }
}

EDIT: On click second Ajax request code as requested:

$(".like").click(function(){

回答1:


have you tried to echo the target? or just simple alert? if that not working it means the target is not sighted, this is specially when the elements are appended. so you need to have a static target

$("#static-target").on("click",".real-target",function(){
 //do here
});


来源:https://stackoverflow.com/questions/59707409/jquery-ajax-total-likes-not-updating-for-post-when-pressing-like-button

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!