I made a simple Ajax vote script for the posts of users: + 1 and -1. Everything works fine, but sometimes with one click for some reason the data sent +3, +6, -2 etc. I made a screenshot of Chrome developer tool. It is seen that that one click is called PHP script multiple times. dot.gif - the buzy animation while data sending.
<script type="text/javascript" src="raitings/jquery.js"></script>
<script type="text/javascript">$(function() {$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='down')
{
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
$.ajax({type: "POST", url: "raitings/down_vote.php", data: dataString, dataType : "html", cache: false, success: function(html)
{ parent.html(html);}
});
}
else
{
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
$.ajax({type: "POST", url: "raitings/up_vote.php", data: dataString, dataType : "html", cache: false, success: function(html)
{ parent.html(html);
} });
}
return false;
});
});
</script>
<?php
echo "<div class=\"box1\"><div class=\"up\"><a href=\"#\" class=\"vote\" title=\"+ 1\" alt=\"+ 1\" id=".$row["id"]." name=\"up\">".$up."</a></div>"
."<div class=\"down\"><a href=\"#\" class=\"vote\" title=\"- 1\" alt=\"- 1\" id=".$row["id"]." name=\"down\">".$down."</a></div></div>
";
When user have voted you should disable your controls. So Just add some blocking flag (variable, cookie, etc.):
$(function() {
var isUserVoted = false;
$(".vote").click(function() {
if (isUserVoted) {
return false;
}
isUserVoted = true;
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='down') {
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
$.ajax({type: "POST", url: "raitings/down_vote.php", data: dataString, dataType : "html", cache: false, success: function(html)
{ parent.html(html);}
});
} else {
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
$.ajax({type: "POST", url: "raitings/up_vote.php", data: dataString, dataType : "html", cache: false, success: function(html) { parent.html(html);
} });
}
return false;
});
});
Instead on jquery click event try to write onclick="function_name();" for a href..
for e.g. ...