Initially, there was a smoothly working "like button" with the following appearance:
<a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <span><?php echo likes($row['id']); ?></span></a>
Below is the Ajax code snippet:
<script>
$(function(){
$(".like").click(function(){
var postid = $(this).attr("id");
$.ajax({
type:'POST',
url:'addlike.php',
data:'id='+postid,
success:function(data){
if(data=="you already liked this post"){
alert(data);
}
else{
$('a#'+postid).html(data);
}
}
});
});
});
</script>
Upon successful AJAX request, addlike.php will return two possible responses - an alert saying "you already liked this post" if the user had already liked it, or the updated number of likes. For instance, if there were 10 likes and the user clicks the button, $('a#'+postid).html(data) would update the count to 11, where 'data' represents the new like count, and $('a#'+postid) selects the clicked "like button".
Due to certain requirements, I need to use data-id instead of id for the button's HTML id attribute. More details can be found here.
Now, post a successful AJAX response, how can I target the element with a data-id instead of id? I attempted the following methods:
$('a#data-id'+postid).html(data);
$('.[data-id="postid"]').html(data);
$('a[data-id='+postid']').html(data);
$('a#'+"[data-id=postid"]).text(data);
Unfortunately, none of these approaches seems to work. Any help will be greatly appreciated.