Here is my HTML/PHP:
<p>
<span data-good="<?php echo $row['good']; ?>" data-wasVoted="<?php echo $row['wasVoted']; ?>" data-review="<?php echo $row['review_id']; ?>" class="upvote">Votes (<span class="good"><?php echo $row['good']; ?></span>)</span>
</p>
This looks like a mess, I apologize but it is test code.
To the user this will look like this in the output:
Votes (3) // 3 is just an example number.
This will be clickable. I want the user to click on it, and if they have already voted on this, 3 becomes 2. If they have not, 3 becomes 4. This is determined by the data-wasVoted
attribute. It is 1 if they have and 0 if they haven't. (there will be styling so user can identify if they have upvoted or not).
Sending this info to server and getting back what I need is all set up. I just can't figure out a good way to grab the right number since this is a looped list of generated HTML. So there are a string of dynamic vote buttons.
Here is my jQuery:
var review_id = $(this).data('review');
var was_voted = $(this).data('wasVoted');
var vote_total = $(this).data('good');
var new_text = $('.good');
$.ajax({
url : "php/reviews_upvote.php",
type : "POST",
dataType : "json",
data : {
reviewId : review_id
},
success : function(data) {
if (was_voted == 1) {
vote_total = vote_total - 1;
new_text.text(vote_total);
} else {
vote_total = vote_total + 1;
new_text.text(vote_total);
}
}
});
The first problem is obviously the var new_text
. It's based on a class
that is repeated over and over again. So if you click one, ALL vote numbers change on the page, not just the one you are dealing with. How can I identify the unique attribute of the one I need?
The second issue; since a user can only vote one -- I need to dynamically change the was_voted
var to 0 if it was 1, or 1 if it was 0.
EDIT: Added HTML rendered after php
is called.
<span data-good="2" data-wasvoted="1" data-review="2582" class="upvote">
Votes (<span class="good">2</span>)
</span>
data-good
is the vote total.