Reputation: 538
I want to build a blog witch has like and dislike button. My problem is when user click on like button I can't actually limit him to not do that again and not like the post again and again and again. I use ajax($.post
) with JQuery to insert data.
How can i do that? Do i need to change my database structure?
var did_liked = 0;
$("#insert_like").click(function (e) {
var post_id = $("#post_id").val();
did_liked +=1 ;
if (did_liked == 1) {
$.post("./inc/like.php", {
post_id_like: post_id
}, function (data, status) {
$("#insert_like").text(data);
});
}
});
$("#insert_dislike").click(function (e) {
var post_id = $("#post_id").val();
$.post("./inc/like.php", {
post_id_dislike: post_id
}, function (data, status) {
$("#insert_dislike").text(data);
});
});
With did_liked
I can prevent user to don't like it again but if he refresh the page he can do so.
My db:
Upvotes: 0
Views: 546
Reputation: 3440
Here is some idea to avoid user to add multiple like / dislike by article :
1/ Create a like
table with unique id :
TABLE LIKE
=====================================
id_like | id_user | id_article | like
With an unique id on id_user and id_article
so the same user can't like / dislike the same article twice and like = 1 or 0
2/ Check if you already have one like before insert
In your php, before doing the insert :
select /* your request to check if you have a like for this user in this article */;
Then check if you got something :
if (count ( /* what you fetch */) === 0) {
/* you insert because you have no data */
} else {
/* you don't insert */
}
Btw, you should add
$("#insert_like").attr('disabled', true);
$("#insert_dislike").attr('disabled', true);
when user click so he can't multiple click, and remove the disabled
when your Ajax call is complete.
Upvotes: 1
Reputation: 572
Make a table with userID, LikedPostID, DislikedPostID column. After you can check this:
SELECT LikedPostID, DislikedPostID FROM tblUserLikes WHERE userID='$user'
in PHP
if ($LikedPostID == $thisPostID || $DislikedPostID == $thisPostID) { // make a like or dislike button to disable state }
Upvotes: 1