jeudi 5 février 2015

javascript like button on multiple boxes


I am creating a web app that displays articles/gallery etc and on each article there is a like type button that uses ajax to update the database which is all working great, the issue I am having is getting the like count to change when the button is pressed. It works but it increments by the number of articles that are on the page.


HTML



<div class="imgStats">
<div class="imgLike" id="unlike<?=$img['id'];?>" style="display:none;"><a href="#" class="unlike" id="<?=$img['id'];?>"><img src="img/like-btn.png" align="absmiddle" /></a></div>
<div class="imgLike" id="like<?=$img['id'];?>"><a href="#" class="like" id="<?=$img['id'];?>"><img src="img/-like-btn-outline.png" width="" /></a></div>
</div>


Javascript



$(function() {
$(".like").click(function()
{
var img_id = $(this).attr("id");
var datastring = 'img_id='+ img_id ;

var imgLikeCount = document.getElementById('imgCot'+ img_id).innerHTML;
imgLikeCount++;

$.ajax({
type: "POST",
url: "../../../inc/like.php",
data: datastring,
success: function(html){}
});
$("#like"+img_id).hide();
$("#unlike"+img_id).show();
$("#imgCot"+img_id).html(imgLikeCount);
return false;
});
});


Is this happening because say i have three images on the page each with a like button, the count will go up by 3. Is it because there is three elements with the class like so it would run through the js three times? it that is the case how would you stop this, and only do it once?


Thanks for having a look, it is much appreciated Cheers Shuka





Aucun commentaire:

Enregistrer un commentaire