简体   繁体   中英

How to store votes with cookies in PHP/JS

Somewhere on the web I seen a site that has a basic "like" script for blog posts.

I am trying to replicate it, I am just a little confused. Here is the code I have for the frontend

Javascript, requires jquery

jQuery(document).ready(function() {

function my_reloadLikes(who) {
    var text = jQuery("#" + who).html();
    var patt= /(\d)+/;

    var num = patt.exec(text);
    num[0]++;
    text = text.replace(patt,num[0]);
    jQuery("#" + who).html('<span class="count">' + text + '</span>');
} //reloadLikes


function my_likeInit() {
    jQuery(".likeThis").click(function() {
        var classes = jQuery(this).attr("class");
        classes = classes.split(" ");

        if(classes[1] == "active") {
            return false;
        }
        var classes = jQuery(this).addClass("active");
        var id = jQuery(this).attr("id");
        id = id.split("like-");
        jQuery.ajax({
          type: "POST",
          url: "index.php",
          data: "likepost=" + id[1],
          success: my_reloadLikes("like-" + id[1])
        }); 


        return false;
    });
}

my_likeInit();

});

HTML

.like-count .icon {
    background-position: 0 -19px;
    width: 13px;
    height: 11px;
    float: left;
    margin: 4px 5px 0 0;
}

.like-count a:hover .icon,
.like-count a.active .icon { background-position: -15px -19px; }

.like-count,
.edit-post,
.comment-count {
     float: right;
     margin: 0 0 0 10px;
}

<li class="like-count">
    <a href="#" class="likeThis active" id="like-356">
      <span class="count"><span class="icon"></span>
      <span class="count">397</span></span>
    </a>
</li>

Here is what I have gathered so far...

my_likeInit() function

  • Adds a click event to the .likeThis class
  • Saves the likeThis class to a variable
  • Splits the value of .likeThis if there is a " " space, it is checking to see if there is an "active" class attached to it or not
  • If .active is found then it dies as this has alread been voted/liked for
  • If not, it adds the .active class to .likeThis
  • Then it gets the id=like-123number
  • Splits it and cuts of the "like-" part and gets the number
  • Send the id number to the PHP script as "likepost=NUMBERHERE
  • On success from the AJAX request, it runs the my_reloadLikes() function, passing in the value "like-NUMBERHERE"

my_reloadLikes() function

  • I wont go into it but you can see, it finds the div by ID number and adds the number and then updates the number on the page

When I run firebug, under Net / XHR I get this,

Request Headers
POST: likepost=811 //in this case, I had clicked to vote on id 811 w3tc_referrer=http%3A%2F%2Ftest.testdomain.com%2F%3Ftheme%3Dtest; 795=795; 835=835; 832=832 w3tc_referrer=http%3A%2F%2Ftest.testdomain.com%2F%3Ftheme%3Dtest; 795=795; 835=835; 832=832 w3tc_referrer=http%3A%2F%2Ftest.testdomain.com%2F%3Ftheme%3Dtest; 795=795; 835=835; 832=832 This is some sort of cookie being set that appears to save the id of all the things I vote/like on.

Response Headers Set-Cookie 811=811; expires=Sat, 13-Jan-2807 11:04:20 GMT; path=/ Set-Cookie 811=811; expires=Sat, 13-Jan-2807 11:04:20 GMT; path=/ Set-Cookie 811=811; expires=Sat, 13-Jan-2807 11:04:20 GMT; path=/ Here I can see the id is definitively being saved to a cookie. TO me it looks like this would be it's OWN cookie, but above it shows multiple values in the cookie, so are they just appended onto the end? All those ID's that I voted on above were on the same page, possibly it is 1 cookie per page, hopefully just 1 per site...


So that is as far as I am, I have basically dissected the code and I fully understand everything above, now on the the back-end which will be out of my head and where I need help

Ok when a page loads, I will populate the like count from a MySQL database, I know how to do the backend of adding the values and getting the values for this script. The cookie part is where I am a little confused.

I just did another test, I now see that the script DOES save each vote into a seperate cookie, so if I vote on 100 items I have 100 cookies for that site, that doesn't seem right?

Is there a better way? The cookies identify if I have already voted and prevent me from voting again until my cookies are cleared. This will be on a wordpress blog so the users will not be logged in, so there isn't a lot of options besides cookies and/or IP address.

Questions

  1. Is there a better way to keep track of which items I have voted/liked instead of a cookie for each item?
  2. Some sample PHP code to check for a cookie so I can add a "active" class to items that are already voted on (based on if they have a cookie for it)
  3. ON a wordpress blog, how can I POST to index.php?likepost=1234 or am I better of just posting to a different URI page and doing a DB connection manually instead of utilizing the wordpress stuff?

========= Thanks for any insight on the cookie issues, I realize I kinda rambled on there a bit.

Yes, definitely do this in the database. As I said earlier, cookies can be modified and really screw up your logic. Create a simple database table:

-------------------------------
|            likes            |
-------------------------------
| like_id | post_id | user_id |
-------------------------------

Create a primary key (auto increment) on like_id , so you can easily delete rows. Then create a UNIQUE index on post_id, user_id , which will help in data concurrency as it is impossible for a user to like the same post more than once at the database level.

However, you can omit like_id if you prefer. It is not necessary, and all up to your preference.

Now, you can query out any information you need. Say, the number of likes for a post:

SELECT COUNT( *) FROM likes WHERE post_id = $post_id

Or to determine whether or not a user liked this post:

SELECT like_id FROM likes WHERE post_id = $post_id AND user_id = $user_id

To address the rest of your questions:

  1. As I said earlier, serialization is a common and great practice to store multiple entries in one entity. Essentially you are saving the state of an object (or array) so that it can be restored later. However, if you use the DB, you won't need to serialize a JS array / object, but it is good to know about as it comes in handy.
  2. Add an active class based on a query from the database, see above.
  3. Definitely POST to index.php?likepost=1234. This maintains a single entry point into your application, which WordPress provides for you. The benefits for this are obvious - Let WordPress setup your connection to the DB and provide you with all the functionality you need instead of reinventing the wheel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM