Trey Copeland
Trey Copeland

Reputation: 3527

How to use jQuery to allow the user to only vote once?

I have an app that allows users at the same company on the same login to vote on specific items, therefore I'm unable to use IP to control how many times the user votes. How can I use jQuery to allow the user to only vote once?

jQuery:

$("#xmlDiv").on("click", ".upvote", function(e) {
            var id = $(this).attr("id");
            var main = $(this);
            $.ajax({
                type: 'post',
                url: 'includes/upvote.php',
                data: { "id":id }, 
                success(data) {
                main.parent().find("div.votenum").html(data);
                },
                error: function (xhr, textStatus, error) {
                    alert("Sorry!");
                }
            });
        });

$("#xmlDiv").on("click", ".downvote", function(e) {
        var main = $(this);
        var id = $(this).attr("id");
        $.ajax({
            type: 'post',
            url: 'includes/downvote.php',
            data: { "id":id }, 
            success(data) {
                main.parent().find("div.votenum").html(data);
            },
            error: function (xhr, textStatus, error) {
                alert("Sorry!");
            }
        });
    });

HTML:

<img src="arrow-up-01-20.png" style="float:right;" class="upvote" id="5">
<img src="arrow-down-01-20.png" id="5" class="downvote" style="float:right;"> 
<div class="votenum" style="float:right;" id="5">12</div>

Upvotes: 0

Views: 192

Answers (2)

Goose
Goose

Reputation: 4821

jQuery can't retain memory across page loads. Refreshing the page makes any logic start from the start. You're solution is going to have to involve server logic.

As far as how to actually do this, if you can't use separate accounts or IPs, perhaps you could identify user by device, browser, and other identifying digital fingerprints. There are a lot and you can make a relatively secure vote, however, anyone with know how would be able to cheat on a vote that doesn't involve secure separate accounts.

Upvotes: 0

user3401335
user3401335

Reputation: 2405

When the user click on upvote, you can add a class to the div voted

main.addClass("voted");

and you can check with hasClass("voted")

$("#xmlDiv").on("click", ".upvote", function(e) {
        var id = $(this).attr("id");
        var main = $(this);

        if(main.hasClass("voted"))
          return;

        main.addClass("voted");

        $.ajax({
            type: 'post',
            url: 'includes/upvote.php',
            data: { "id":id }, 
            success(data) {
            main.parent().find("div.votenum").html(data);
            },
            error: function (xhr, textStatus, error) {
                alert("Sorry!");
            }
        });
    });

I suggest to control again at server side

Upvotes: 1

Related Questions