The main problem is every time the users will click the heart button for likes, they can spam the like button and the likes will also increase every time you click the like button.
here's my php code:
`
<?php
if(isset($_POST['how'])){
session_start();
$user_id=$_SESSION['userId'];
$post_id=$_POST['data'];
$con = new mysqli("localhost","root","","tattoo_db");
$sql1="SELECT `design_id`, `count` FROM `works` WHERE design_id='$user_id' and
count='$post_id'";
$res=$con->query($sql1);
if($res->num_rows == 0){
$sql2="UPDATE `works` SET `count`=count+1 WHERE design_id='$post_id'";
if($con->query($sql2)){
$sql3="INSERT INTO `works`(`design_id`, `count`) VALUES ('$user_id','$post_id)";
if($con->query($sql3)){
echo "liked";
}
}
}else if($res->num_rows==1){
$sql2="UPDATE `works` SET `count`=count-1 WHERE design_id='$post_id'";
if($con->query($sql2)){
$sql3="DELETE FROM `works` WHERE design_id='$user_id' and count='$post_id'";
if($con->query($sql3)){
echo "disliked";
}
}
}
}
?>
`
and this is my javascript code:
`
$(document).ready(function(){
$(".like").click(function(){
var design_id=$(this).attr("title");
var i=$(this).children(".like_icon").attr("src");
if(i=="admin/works/heart.svg"){
$(this).children(".like_icon").attr("src","admin/works/red-heart.svg");
$(this).children("span").text("liked");
}else if(i=="admin/works/red-heart.svg"){
$(this).children(".like_icon").attr("src","admin/works/heart.svg");
$(this).children("span").text("unliked");
}
$.post("header/get.php",{data:design_id,how:'c'});
});
});
`
I want to limit the users to one per like to prevent multiple likes from every users when they click the like button.
Related
I'm working on a Like button. It's working just fine unless user refresh the page. When page is not refreshed the like button itself change the style and add 1 to the like count if user click on it. But when the page is refreshed the like button remain the like count and the previous style then add 1 to the like count and change to the new style if user click on it. That's the problem.
The like button looks like this:
Here is the Javascript code:
function addLikes(id,action) {
$.ajax({
url: "like.php",
data:'post_id='+id+'&action='+action,
type: "POST",
success: function(data){
var likes = parseInt($('#likes-'+id).val());
switch(action) {
case "like":
$('#like_area'+id).html('<i id="like'+id+'" class="fas fa-thumbs-up react"></i> Thích');
$('#like_area'+id).attr("onclick", "addLikes("+id+",'unlike')");
likes = likes+1;
$('#like_area'+id).addClass("liked");
break;
case "unlike":
$('#like_area'+id).html('<i id="like'+id+'" class="far fa-thumbs-up react"></i> Thích');
$('#like_area'+id).attr("onclick", "addLikes("+id+",'like')");
$('#like_area'+id).removeClass("liked");
likes = likes-1;
break;
}
$('#likes-'+id).val(likes);
if(likes>0) {
$('#people_liked'+id).html(kFormatter(likes));
$('#user_liked'+id).attr("style", "display:block;");
} else {
$('#user_liked'+id).attr("style", "display:none;");
}
}
});
}
Here is the PHP code in like.php:
<?php
session_start();
require $_SERVER['DOCUMENT_ROOT'] . '/require/serverconnect.php';
$username = $_SESSION['username'];
$post_id = $_POST['post_id'];
$action = $_POST['action'];
if(!empty($post_id)) {
switch ($action) {
case 'like':
$query = "INSERT IGNORE INTO tintuc_post_likes (username_of_like, liked_post_id) VALUES ('$username','$post_id')";
$result = mysqli_query($con, $query);
break;
case 'unlike':
$query = "DELETE FROM tintuc_post_likes WHERE username_of_like = '$username' AND liked_post_id = '$post_id'";
$result = mysqli_query($con, $query);
break;
}
}
?>
PHP Select code in index.php:
<?php
$sql = "SELECT tintuc_posts.id, tintuc_posts.author, tintuc_posts.content, tintuc_posts.timeofpost, tintuc_posts.has_comment, tintuc_posts.avatar, tintuc_posts.has_image, tintuc_posts.image, tintuc_posts.username, tintuc_posts.c4id, COUNT(tintuc_post_likes.like_id) as likes, GROUP_CONCAT(accounts.name separator '|') as liked_by
FROM tintuc_posts
LEFT JOIN tintuc_post_likes
ON tintuc_posts.id = tintuc_post_likes.liked_post_id
LEFT JOIN accounts
ON tintuc_post_likes.username_of_like = accounts.username
GROUP BY tintuc_posts.id
ORDER BY tintuc_posts.id DESC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
?>
Here is the tables:
As this is probably your answer:
In your screenshot, you have the yellow thumb in the tool bar, is this what you want to be selected/highlighted when they page refresh? To show they have already liked it?
Assuming this is the case, when you run the code to draw that button, you need to get a list of users who have like it, and compare to the current user, and then if current user is in that list, add the "selected" class (or whatever you do on click initially) so the button looks selected.
I am not a PHP developer, but in pseudo code would be something like:
var hasLiked = ListOfUserLinks.IndexOf(currentuserId) >= 0;
<button name="like" class="button <%hasLiked ? 'likedState' : ''%>" />
You can see you just adjust the classes based on whether the user has liked it, but it is done at page load time, as this is the initial state of the page.
I am creating a kind of messaging system with php and jQUERY, when you click on users profile and hit the messaging button it take us to the message page, it takes about 2sec to load previous message, so I added a code to scroll to bottom of the div class containing all message item once the ajax is loaded, to show latest messages , but the problem I am having is when I try to scroll up back I am having issues , the moment i try to scroll up due to the code i added it goes down on its own, any solution would be well appreciated.
Here is my JQ code - if there is anything else I can provide to help me solve this issue, I would do so quickly.
$(document).ready(function(){
/*post message via ajax*/
//get message
var c_id = $("#conversation_id").val();
//get new message every 2 second
setInterval(function(){
$(".display-message").load("get-message-ajax.php?c_id="+c_id , stateChange);
}, 2000);
});
function stateChange() {
var newstate = true;
if(newstate = true){
$(".conversation_history.clearfix").animate({
scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight
}, 1000)} else {
$(".conversation_history.clearfix").end();
var newstate = false;
}
}
Code from get_message-ajax.php
<?php
include 'db.php';
include 'function.php';
/*Get Message*/
if(isset($_GET['c_id'])){
$conversation_id = base64_decode($_GET['c_id']);
$querynew = "SELECT * FROM `messages` WHERE conversation_id='$conversation_id'";
$mysqli_q_new = mysqli_query($connection, $querynew);
confirmQuery($mysqli_q_new);
if (mysqli_num_rows($mysqli_q_new) > 0 ){
while($user_real_info = mysqli_fetch_assoc($mysqli_q_new)){
$trap_user_from = $user_real_info['user_from'];
$trap_user_to = $user_real_info['user_to'];
$trap_user_message = $user_real_info['message'];
$querynew2 = "SELECT profile_image,firstname FROM `users` WHERE id='$trap_user_from'";
$mysqli_q_new2 = mysqli_query($connection, $querynew2);
confirmQuery($mysqli_q_new2);
$user_fetch = mysqli_fetch_assoc($mysqli_q_new2);
$user_form_username = $user_fetch['firstname'];
$user_form_img = $user_fetch['profile_image'];
?>
<div class='conversation_history_inner clearfix'>
<span><?php echo $user_form_username; ?> </span>
<div class='converstion_history_image img-is-responsive pull-left'>
<?php echo getUserImage($user_form_img) ?>
</div>
<div class='converstion_history_chat'>
<p><?php echo $trap_user_message; ?></p>
</div>
</div>
<?php
}
}
} else {
echo 'nth found';
}
?>
I'm assuming you only want to scroll down when it gets the first message. If so, I would suggest changing the stateChange function into this:
var scrolled = false;
function stateChange() {
if(!scrolled){
$(".conversation_history.clearfix").animate({scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight}, 1000);
scrolled = true;
}
}
This will make it only scroll down the first time it gets a new message instead of every time like it currently does.
The content is scrolling to bottom automatically because you have used setInterval function which will trigger at a constant interval of time. Use setTimeOut instead it will call only once after the specified time. Look here for more details
I am counting the clicks on anchors and store the number of clicks in a .txt file.
When click on an anchor, the number increases by 1.
I am not using a user management system, so to prevent multiple clicks on an anchor by a user, i need to store a cookie.
But i do have multiple anchors. If a user clicks on anchor 1, the number of click events on anchor 1 increases by 1. He should not have the possibility to click a second time on anchor 1, at least: it should not increase by 1 anymore.
But for that user, he still must be able to click on anchor 2 and anchor 3 and it should increase with 1. And after this, also these anchors should not increase by 1 anymore when user clicks on it.
How can i achieve this?
This is my html;
<?php
$clickcount = explode("\n", file_get_contents('counter.txt'));
foreach($clickcount as $line){
$tmp = explode('||', $line);
$count[trim($tmp[0])] = trim($tmp[1]);
}
?>
Like
<span class="click-count"><?php echo $count['count1'];?></span> likes.
Like
<span class="click-count"><?php echo $count['count2'];?></span> likes.
Like
<span class="click-count"><?php echo $count['count3'];?></span> likes.
The js:
$(document).on('click', '.click-trigger', function()
{
var data = {'id':$(this).attr('data-click-id')};
var count = $(this).next(".click-count");
$.ajax({
type : 'POST',
url : 'counter.php',
data : data,
success : function(data)
{
$(".click-count").fadeIn(500).show(function()
{
count.html(data);
});
}
});
return false;
});
And this is file counter.php
$file = 'counter.txt'; // path to text file that stores counts
$fh = fopen($file, 'r+');
$id = $_REQUEST['id']; // posted from page
$lines = '';
while(!feof($fh)){
$line = explode('||', fgets($fh));
$item = trim($line[0]);
$num = trim($line[1]);
if(!empty($item)){
if($item == $id){
$num++; // increment count by 1
echo $num;
}
$lines .= "$item||$num\r\n";
}
}
file_put_contents($file, $lines);
fclose($fh);
The file counter.txt looks like this:
count1||36
count2||124
count3||12
You can use serialize on an array of item numbers when setting the cookie value from php, and unserialize when reading the cookie. You will get an array of integers and can check with in_array whether the user has already clicked the link.
when we are inserting the value there is a column name code that is auto generating in mysql. I want to display the last inserted value code column in pop up window.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
require_once 'db.php';
// Escape user inputs for security
$company = mysqli_real_escape_string($test_db, $_POST['company']);
$project = mysqli_real_escape_string($test_db, $_POST['project']);
$revision = mysqli_real_escape_string($test_db, $_POST['revision']);
// attempt insert query execution
$sql = "INSERT INTO live (company, project, revision, code) VALUES ('$company', '$project', '$revision', '')";
if(mysqli_query($test_db , $sql)){
echo '
<script type="text/javascript">
alert("i want to show last inserted code here and redirected to a page on clicking close button");
</script>';
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($test_db);
}
// close connection
mysqli_close($test_db);
?>
Assuming that your "live" table has a primary key auto-increment column, then this should work:
if(mysqli_query($test_db , $sql)){
echo '
<script type="text/javascript">
alert("ID of last inserted row: '.mysqli_insert_id($test_db).'");
</script>';
}
I am trying to use jQuery to pass some values to session variables when buttons are clicked on. Each button has unique values and I need to display values from both buttons when both are clicked.
The problem I am having is that only one set of values (from the most recent button clicked) is translated as a session variable - if I click the first button, the first values are passed to the session backend fine, but clicking the second button afterwards results in only the second values being passed.
My jquery looks like this:
$button_one.click(function(e) {
e.preventDefault();
var var_one = "value1";
var var_two = "value2";
$.post("sessions.php", { 'session_var_one': var_one, 'session_var_two': var_two });
});
$button_two.click(function(e) {
e.preventDefault();
var var_three = "value3";
var var_four = "value4";
$.post("sessions.php", { 'session_var_three': var_three, 'session_var_four': var_four });
});
The sessions.php is very simple:
<?php
session_start();
$_SESSION['value_one'] = $_POST['session_var_one'];
$_SESSION['value_two'] = $_POST['session_var_two'];
$_SESSION['value_three'] = $_POST['session_var_three'];
$_SESSION['value_four'] = $_POST['session_var_four'];
?>
And I have a simple page set up to display the session values:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
echo '<h5>' . $_SESSION['session_var_one'] . '</h5>';
echo '<h5>' . $_SESSION['session_var_two'] . '</h5>';
echo '<h5>' . $_SESSION['session_var_three'] . '</h5>';
echo '<h5>' . $_SESSION['session_var_four'] . '</h5>';
?>
</body>
</html>
This page displays only the two values of the button that was last clicked on - instead of displaying both sets of values if both buttons are clicked on.
I am guessing that having two separate AJAX requests, one within each click function, may be the problem here - when button two is clicked after button one, it "forgets" the first request and thus the values are not recorded.
I have worked around this problem by sending each of the button click values to a different session php page (i.e. button_one goes to sessions_one.php and button_two goes to sessions_two.php) but I would prefer not to have to create a new place to store the session values for each button. I plan on adding more buttons and it seems like bad practice to have each button have a separate home for its stored values.
How can I rewrite my AJAX requests and/or sessions.php so that I can store all of the values from each button click? Thank you for any guidance, I'm very new to PHP and AJAX in general!
If a $_POST variable is not provided, your code will just put NULL in the corresponding $_SESSION variable. To prevent that, check that it is provided before doing so:
<?php
session_start();
if( isset($_POST['session_var_one']) ){
$_SESSION['value_one'] = $_POST['session_var_one'];
}
if( isset($_POST['session_var_two']) ){
$_SESSION['value_two'] = $_POST['session_var_two'];
}
if( isset($_POST['session_var_three']) ){
$_SESSION['value_three'] = $_POST['session_var_three'];
}
if( isset($_POST['session_var_four']) ){
$_SESSION['value_four'] = $_POST['session_var_four'];
}
?>
I think you really want something like this so the session data stays if you aren't passing it a new value.
$_SESSION['value_one'] = (!empty($_POST['session_var_one'])) ? $_POST['session_var_one'] : $_SESSION['value_one'];
$_SESSION['value_two'] = (!empty($_POST['session_var_two'])) ? $_POST['session_var_two'] : $_SESSION['value_two'];
$_SESSION['value_three'] = (!empty($_POST['session_var_three'])) ? $_POST['session_var_three'] : $_SESSION['value_three'];
$_SESSION['value_four'] = (!empty($_POST['session_var_four'])) ? $_POST['session_var_four'] : $_SESSION['value_four'];
To display you should to call to session not post and it will be like this:
<?php
echo '<h5>' . $_SESSION['value_one'] . '</h5>';
echo '<h5>' . $_SESSION['value_two'] . '</h5>';
echo '<h5>' . $_SESSION['value_three'] . '</h5>';
echo '<h5>' . $_SESSION['value_four'] . '</h5>';
?>