Reputation: 484
I'm using a ajax voting system in one of my projects. Problem is I'm using a div with a id to display the votes. So when ever someone click vote up or down in any of the posts (there are so many posts in one page. it is a php loop) it always end up displaying in the 1st div. This is my code
$(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id=' + id;
var parent = $(this);
if (name == 'up') {
$(this).fadeIn(200).html;
$.ajax({
type: "POST",
url: "vote_up.php",
data: dataString,
cache: false,
success: function(html) {
$("#display-vote").html(html);
}
});
} else {
$(this).fadeIn(200).html;
$.ajax({
type: "POST",
url: "vote_down.php",
data: dataString,
cache: false,
success: function(html) {
$("#display-vote").html(html);
}
});
}
return false;
});
});
HTML
<div class="vote-box">
<a href="" class="vote" id="<?php echo $PostId; ?>" name="up"></a>
<div id="display-vote"><?php echo $Votes; ?></div>
<a href="" class="answer-vote down" id="<?php echo $PostId; ?>" name="down"></a>
</div>
Is there is anyway that i can display votes in the correct place? Really appropriate any help.
Upvotes: 1
Views: 553
Reputation: 2786
Id attribute should be unique. if you have multiple elements with same id, when doing something like this $('#myNotSoUniqueId')
will always return you first one.
As a quick solution I would recommend instead of
<div id="display-vote"><?php echo $Votes; ?></div>
have something like
<div class="display-vote" data-id="<?php echo $PostId; ?>">
<?php echo $Votes; ?>
</div>
and in javascript to have something like this:
$(".display-vote[data-id='" + postId +"'])
to select element by specific data-id attribute
Upvotes: 1
Reputation: 8246
Surely just don't use an ID?
HTML:
<div class="vote-box">
<a href="" class="vote" id="<?php echo $PostId; ?>" name="up"></a>
<div class="display-vote"><?php echo $Votes; ?></div>
<a href="" class="answer-vote down" id="<?php echo $PostId; ?>" name="down"></a>
</div>
JavaScript:
success: function(html) {
$(this).parent().find('.display-vote').html(html);
}
Upvotes: 3