Search code examples
javascriptjqueryajaxxmlhttprequest

View response data from AJAX request for multiple elements


I have a like system in my website. Each message has a Like button and a counter next to it.
Now when someone clicks the Like button it should immediately change to 1, and if another user clicks the same message it would change to 2 and so on for each individual message.

I created the AJAX functions required to do this, but I am using document.getElementById which only retrieves the first instance found and views the response from the ajax request.

How can I make it so that it is viewed for each individual message?

Here is my AJAX requests:

jQuery(document).ready(function($){
    $('.msg-icon').on('click', function(e){
    e.preventDefault(); 
 
    var reply_id = $(this).find('input[name="replymsg"]').val();
   var request = reply(reply_id); 
   
    request.done(function() { 
      checkLikes(reply_id);
    });
  });
});
   
  
function reply(reply_id) {
  return $.ajax({ 
    data: reply_id, 
    type: "post", 
    url: "replyfavorite.php?replymsg="+reply_id, 
  });
}

function checkLikes(reply_id) {
  return $.ajax({
    data: { reply: reply_id },
    type: "get",
    url: "checkLikes.php?reply=" + reply_id,
    success: function(data) {
      document.getElementById('likesCount').innerHTML = data; //what can i change here to make the data go to each clicked button?
    }
  });
}

here is my html button that users click for each message:

<a href="" class="msg-icon" >

<i class="fas fa-heart fa-lg" id="favBtn" style="color: #e74f4e !important;"  >
  <span id="likesCount"><?php echo $row3['likes_count'] ?>
</span></i></a>

the code is working fine my only problem is with how to let the response go to the clicked message button only.


Solution

  • As you noticed, ID should be unique. Instead of using document.getElementById('likesCount').innerHTML = data;
    use the data-* attribute

    I.e:

    <span data-id="536">12</span>
    

    than inside the jQuery success do like:

    success: function(data) {
      $(`[data-id="${reply_id}"]`).text(data)
    }
    

    and such will update any number of data-id="" elements on the page with the newest likes count.

    PS: if you want to make your counts "live" - instead of using AJAX which is one roundtrip-only (request → response), you could use https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API

    By using Web Sockets you're making sure an initial handshake is made between any client and your server and than small packets are shared between the two - for multiple clients simultaneously. That way you don't need to have recurring AJAX intervals - and all your guests will see the likes change value "automagically".