After button clicked, save to MySQL then display CSS highlight - php

I've got a Rating function that does as follows: Once a user clicks the +1 button, the rating goes up by 1, and saves to MySQL. What I'd like for it to do is once clicked, it changes
the background to a different color as shown below..
( What I'd like for it to do is the "once clicked" ) at the current moment it just updates the number with the background being white)
NOTE: I'm just asking for suggestions or some way to lead me in the right direction, thank you in advance.
Without being clicked:
Once clicked:
php/html form: to submit the +1
<div class="up vote" name="voteUp" id="<?php echo $post_iD;?>">
<div class="wrapper">+<?php echo $VoteRate;?></div>
</div>
AJAX: to update the button
$(function()
{
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='voteUp')
{
$.ajax(
{
type: "POST",
url: "voting/up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
up_vote.php: submit from the ajax
$ip = $_SERVER['REMOTE_ADDR'];
if($_POST['id'])
{
$sth = $db->prepare("SELECT add_iP FROM PostsRating WHERE post_iD_fk = :id AND add_iP = :ip");
$sth->execute(array(':id' => $_POST['id'], ':ip' => $ip));
if( $sth->fetchColumn() == 0)
{
$sth = $db->prepare("UPDATE posts set voteUp = voteUp+1 where post_iD = :id");
$sth->execute(array(':id' => $_POST['id']));
$sth = $db->prepare("INSERT into PostsRating (post_iD_fk, add_iP) VALUES (:id, :ip)");
$sth->execute(array(':id' => $_POST['id'], ':ip' => $ip));
} else {
$sth = $db->prepare("UPDATE posts set voteUp = voteUp-1 where post_iD = :id");
$sth->execute(array(':id' => $_POST['id']));
$sth = $db->prepare("DELETE FROM PostsRating WHERE post_iD_fk = :id AND add_iP = :ip");
$sth->execute(array(':id' => $_POST['id'], ':ip' => $ip));
}
$sth = $db->prepare("SELECT voteUp FROM posts WHERE post_iD = :id");
$sth->execute(array(':id' => $_POST['id']));
$row = $sth->fetch();
echo $row['voteUp'];
}

In your success callback, why not just set a class to the parent and then update the .wrapper?
success: function(html)
{
parent.addClass("blue");
parent.find(".wrapper").html("+ " + html);
}
When the user refreshes the page and you want to continue to show the blue, you would simply:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$sth = $db->prepare("SELECT add_iP FROM PostsRating WHERE post_iD_fk = :id AND add_iP = :ip");
$sth->execute(array(':id' => $post_iD, ':ip' => $ip));
$class = ($sth->fetchColumn()) ? " blue" : "";
?>
<div class="up vote<?php echo $class; ?>" name="voteUp" id="<?php echo $post_iD;?>">
<div class="wrapper">+<?php echo $VoteRate;?></div>
</div>

You can change the success function to add the color with .css("background-color","blue") or if you want to have it always blue if the vote_counter is higher than you can add this to the top of your code:
if (parseInt($("#"+id).children(".wrapper").text()) >= 1) {
$("#"+id).children(".wrapper").css("background-color","blue");
}

First of all, you can not have a class name with a space in it - it will be interpreted as two classes, up and vote.
Within the php you can echo something along the lines of (be sure to set dataType to json)
echo(json_encode(array("success"=>true)));
exit();
After which the jquery can handle the response:
function(result) {
var result_string = jQuery.parseJSON(result);
if(result_string.success) {
$(this).children(".wrapper").css("background-color", "blue")
}
}

Related

PHP no results message still showing when posting data via ajax

I'm creating a comment facility for a blog post using PHP and ajax to post the comment so the page does not refresh after a comment is posted.
This is the code that displays the comments when the page is visited. If there are no comments for the post it displays a notice. This all works.
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
ORDER BY comm.comment_date DESC");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt_result = $stmt->get_result();
if ($stmt_result->num_rows > 0) {
while($row = $stmt_result->fetch_assoc()) {
$comment = $row["comment"];
$comment_date = date_create($row['comment_date']);
$comment_date = date_format($comment_date, ' l jS F Y H:i');
$comment_author = $row["member_screen_name"];
$comments .= "<div class='comment_div'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";
}
}else{
$comments = "<div class='alert alert-primary' role='alert'>Be the first to comment</div>";
}
When the comment form is submitted it calls this function.
$('#submit').click(function (e) {
e.preventDefault();
if (!$('#summernote').summernote('isEmpty')) {
var comment = document.getElementById("summernote").value;
var member_id = 1;
var post_id = 1;
$.ajax ({
type: 'post',
url: 'post_comment.php',
data: {
comment:comment,
member_id:member_id,
post_id:post_id,
},
success: function (response) {
document.getElementById("all_comments").innerHTML=response+document.getElementById("all_comments").innerHTML;
$("#summernote").summernote("reset");
},
});
}else {
alert('Please enter a comment');
}
return false;
});
This is the post_comment.php page
if(isset($_POST['comment'])){
$comments = "";
$comment=$_POST['comment'];
$member_id =$_POST['member_id'];
$post_id =$_POST['post_id'];
if(isset($comment)) {
$stmt = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $post_id, $member_id, $comment);
$stmt->execute();
$entry_id = mysqli_insert_id($conn);
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
AND comm.id = $entry_id
ORDER BY comm.comment_date DESC");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt_result = $stmt->get_result();
if ($stmt_result->num_rows > 0) {
while($row = $stmt_result->fetch_assoc()) {
$comment = $comment;
$comment_date = date_create($row['comment_date']);
$comment_date = date_format($comment_date, ' l jS F Y H:i');
$comment_author = $row["member_screen_name"];
$comments .= "<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";
echo $comments ;
};
exit;
}
}
}else {
header("location: /blog");
exit;
}
If you are the first to comment on a post the comment displays but the "Be the first to comment" notice is still displaying until the page is refreshed.
Try return the response from the server as json. Plus remove the exit and header on your server side.
<script type="text/javascript">
$('#submit').click(function (e) {
e.preventDefault();
if (!$('#summernote').summernote('isEmpty')) {
var comment = document.getElementById("summernote").value;
var member_id = 1;
var post_id = 1;
$.ajax ({
type: 'post',
url: 'post_comment.php',
data: {
comment:comment,
member_id:member_id,
post_id:post_id,
},
dataType : "json",
encode : true,
success: function (data) {
$.each(data, function(index, element){
$('#all_comments').append("<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by " +element.comment_author + "on " + element.post_date+"</p>"+element.comment+"<hr /></div></div>");
});
$("#summernote").summernote("reset");
$('.alert').empty();
},
});
}else {
alert('Please enter a comment');
}
return false;
});
</script>
Then your server side.
<?php
if (isset($_POST['comment'])) {
$comment = $_POST['comment'];
$member_id = $_POST['member_id'];
$post_id = $_POST['post_id'];
$commentsArray = array();
$stmt = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $post_id, $member_id, $comment);
$stmt->execute();
$entry_id = mysqli_insert_id($conn);
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
AND comm.id = ?
ORDER BY comm.comment_date DESC");
$sql->bind_param("ii", $post_id, $entry_id);
$sql->execute();
$sql_result = $sql->get_result();
if ($stmt_result->num_rows > 0) {
while ($row = $stmt_result->fetch_assoc()) {
$comment_date = date_create($row['comment_date']);
$commentsArray[] = array(
'comment' => $comment,
'post_date' = date_format($comment_date, ' l jS F Y H:i');
'comment_author' => $row['member_screen_name']
);
}
}
echo json_encode($commentsArray);
}
Also use the network tab on your browser console to see the response coming from the server.
it is normal for him to behave like this, and at no time will you ask the notification not to appear after the comment.
update your code after the success
$('.alert-primary').hide()

Jquery + Ajax is not working properly, why?

This code will show a counter when there's rows with the status = unread, and it will UPDATE the row to status = read when the user click on the a icon <i class="fas fa-bell"></i>.
The problem is: This is not working propelly, when i click on the <i class="fas fa-bell"></i> it get a delay of 3-9 seconds to update the counter to 0, it update my table instantly, only the counter that get some delay, but sometimes i need to reload the page and click on the icon to update my table, why? What's wrong?
html:
<span class="text-white divCountNT" id="datacount"></span>
script:
<script>
$(document).ready(function(){
$("#datacount").load("select.php");
setInterval(function(){
$("#datacount").load('select.php')
}, 10000);
});
$(document).on('click', '.fa-bell', function (){
$.ajax({
type: "POST",
url: "update.php"
});
});
</script>
select.php:
<?php
require_once 'db.php';
if(!isset($_SESSION))session_start();
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
}
$status = 'unread';
$sql = $conn->prepare("SELECT * FROM noti WHERE status = :status AND user_id = :user_id");
$sql->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();
if($countNT >= 1){
echo $countNT;
}
?>
update.php:
<?php
require_once 'db.php';
if(!isset($_SESSION))session_start();
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
}
$status = 'read';
$sql = $conn->prepare("UPDATE noti SET status = :status WHERE user_id = :user_id");
$sql->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();
echo $countNT;
?>
You dont have a callback function for your ajax call so your table only updates itself with load function. Your ajax call should be something like that :
$.ajax({
type: "POST",
url: "update.php"
}).done(function() {
window.location.reload(true);
});
You can Try with this code It's Working Fine
$.ajax({
type: "POST",
url: "update.php"
success: function(result){
$(body).find("#loadData").html(result);
// $(body).find("#loadData").append(result); //you can also use for append data insted of replace
}
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
check this for use of more methods of AJAX https://www.w3schools.com/jquery/ajax_ajax.asp

removing a table row in php page(not database) and being able to not display it back after reloading the page

I have a page called fetch as belllow :
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row){
$sub_array = array();
$sub_array[] = $row["id"];
$sub_array[] = $row["first_name"];
$sub_array[] = $row["last_name"];
$sub_array[] = '<input type="checkbox" name="confirm" id="'.$row["id"].'" class="btn btn-danger btn-xs delete"></input>';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal"=> $filtered_rows,
"recordsFiltered"=> get_total_all_records(),
"data" => $data
); echo json_encode($output);
and I have a function in the index page that calls the delete page :
$(document).on('click', '.delete', function(){
var user_id = $(this).attr("id");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{user_id:user_id},
success:function(data)
{
alert(data);
dataTable.ajax.reload();
}
});
}
else
{
return false;
}
});
and the delete page looks like this :
if(isset($_POST["user_id"])){
$statement = $connection->prepare(
"DELETE FROM users WHERE id = :id"
);
$result = $statement->execute(
array(
':id' => $_POST["user_id"]
)
);
if(!empty($result))
{
echo 'Data Deleted';
}}
also in the database, I have a table with 4 columns id, first_name, last_name, and check_in (boolean). All I want to do is hide the data displayed from the database if I checkbox them, even after I reload the page. till now I just can delete them. or if I add this function:
$(document).ready(function(){
$("#myTable").on('click','.del',function(){
$(this).closest('tr').hide();
});
});
I can hide them but they came back after I reload the page
#User10 :
(1) Your js at ajax, data:{user_id:user_id}..where's user_id from your table, cause it's just id
(2) better put dataType: "json" (at ajax)

Multiple votes on one page

I have multiple images on the page. Each of the image has thumb up and thumb down and user is able to vote.
The problem is when user vote on the first image vote is changed but when he click on second image the vote is saved in database but isn't updated and changed on the page. When the page is refreshed the vote counter is updated.
Those are the button and votings for the image
$cookie_name = 'vote'.$row['image_id']; // Set up the cookie name
$value = $pdo->prepare('SELECT * FROM tc_tuto_yt_voting_system WHERE image_id= ?'); // BDD query, page ID values
$value->bindParam(1, $row['image_id'], PDO::PARAM_INT);
$value->execute();
$vote = $value->fetch();
echo '
if (isset($_COOKIE[$cookie_name])) {
echo '<div class="vote_up_done oneLine"></div>
<div class="numberVoted oneLine">'.$vote['positive'].'</div>';
}
else
{
echo '<div class="vote_up oneLine" id="voteUp"></div>
<div class="number oneLine" id="positive">'.$vote['positive'].'</div>';
}
if (isset($_COOKIE[$cookie_name])) {
echo '<div class="vote_down_done oneLine"></div>
<div class="numberVoted oneLine">'.$vote['negative'].'</div>';
}
else
{
echo '<div class="vote_down oneLine" id="voteDown"></div>
<div class="number oneLine" id="negative">'.$vote['negative'].'</div>';
}
Vote up&down is ajax driven so this is ajax part
function vote(type, value, image_id) {
var dataFields = {'type': type, 'value': value, 'image_id': image_id}; // We pass the 3 arguments, type: positive or negative ; value=1 ; pageId: here 5
$.ajax({ // Ajax
type: "POST",
url: "ad_vot.php",
data: dataFields,
timeout: 3000,
success: function(dataBack){
$('#' + type).html(dataBack); // Change the new value in id="positive" or id="negative" DIV
$('#voteUp').attr('class', 'vote_up_done oneLine'); // Change image by design/vote-up-done.png grey icon
$('#voteDown').attr('class', 'vote_down_done oneLine'); // Change image by design/vote-down-done.png grey icon
$('#positive').attr('class', 'numberVoted oneLine'); // Change the number's color by a grey one for the "positive" DIV
$('#negative').attr('class', 'numberVoted oneLine'); // Change the number's color by a grey one for the "negative" DIV
$('#message').html('<div id="alertFadeOut" style="color: green">Your vote is added!</div>'); // Diplay message with a fadeout
$('#alertFadeOut').fadeOut(3000, function () {
$('#alertFadeOut').text('');
});
},
error: function() {
$('#message').text('Vote fail. Please try again.');
}
});
}
UPDATE: vote and update
if( $result > 0) {
$query = $pdo->prepare('UPDATE tc_tuto_yt_voting_system SET '.$type.' = '.$type.' + 1 WHERE image_id= :image_id');
$query -> execute(array(
":image_id" => $_POST['image_id']
));
}
else
{
$type = $_POST['type'];
$value = $_POST['value'];
$image_id = $_POST['image_id'];
$query = $pdo -> prepare("INSERT INTO tc_tuto_yt_voting_system (image_id,positive,negative)
VALUES (:image_id, :positive, :negative)");
$query -> execute(array(
":image_id" => $_POST['image_id'],
":positive" => '0',
":negative" => '0'
));
$query = $pdo->prepare('UPDATE tc_tuto_yt_voting_system SET '.$type.' = '.$type.' + 1 WHERE image_id= :image_id');
$query -> execute(array(
":image_id" => $_POST['image_id']
));
}
$value = $pdo->prepare('SELECT * FROM tc_tuto_yt_voting_system WHERE image_id= ?'); // BDD query, page ID values
$value->bindParam(1, $_POST['image_id'], PDO::PARAM_INT);
$value->execute();
$result = $value->fetch();
$expire = 24*3600; // 1 day
setcookie('vote'.$image_id, 'voted', time() + $expire, '/'); // Place a cookie
echo $result[$type];
A better answer:
Don't store the votes in cookie. The user can change it, delete it, and he'll be able to vote again. Create a table in your db, and insert a row when the user votes.
Don't use onclick attribute. Use jQuery's .on/.bind/.click.
As tehy've already explained you, there cannot 2 or more elements on the page with the same id. You need to use classes.
As I've told you, don't use SET '.$type.' = '.$type.' + 1 unless you check what's $type's value. $_POST['type'] can be positive = 1; DROP TABLE tc_tuto_yt_voting_system;.
If registering is required for voting:
CREATE TABLE user_votes (
user_id INT(11) UNSIGNED NOT NULL,
image_id INT(11) UNSIGNED NOT NULL,
vote TINYINT(3) UNSIGNED NOT NULL
)
$user_votes = $db->prepare("SELECT image_id, vote FROM user_votes WHERE user_id = ?");
$user_votes->bindValue(1, $_SESSION["user_id"], PDO::PARAM_INT);
If not:
CREATE TABLE user_votes (
user_ip VARBINARY(16) UNSIGNED NOT NULL,
image_id INT(11) UNSIGNED NOT NULL,
vote TINYINT(3) NOT NULL
)
$user_votes = $db->prepare("SELECT image_id, vote FROM user_votes WHERE user_id = INET6_ATON(?)");
$user_votes->bindValue(1, $_SERVER["REMOTE_ADDR"], PDO::PARAM_STR);
Then display the images, and votes:
$user_votes->execute();
$u_votes = [];
while ($vote = $user_votes->fetch())
$u_votes[$vote->image_id] = $vote->vote;
$images = $db->prepare("SELECT * FROM images");
$images->execute();
while ($img = $images->fetch())
{
$is_voted = isset($u_votes[$img->id]);
$vote = $is_voted ? ($u_votes[$img->id] ? "down" : "up") : "";
echo '<img src="'.$img->filename.'" />
<div class="vote" data-image-id="'.$img->id.'">
<div class="vote_down'.($vote == "down" ? " voted" : "").'"></div>
<div class="number positive">'.$img->positive.'</div>
<div class="vote_up'.($vote == "up" ? " voted" : "").'"></div>
<div class="number negative">'.$img->negative.'</div>
</div>';
}
JS:
$(document).on("click", ".vote .vote_down, .vote .vote_up", function(e)
{
if ($(e.target).is(".voted"))
return;
var that = $(this),
div = that.parent(),
type = that.is(".vote_up") ? "positive" : "negative",
id = div.attr("data-image-id");
$.ajax({
type: "POST",
url: "ad_vot.php",
data: {
tpye: type,
image_id: id
}
timeout: 3000,
success: function(dataBack) {
that.addClass("voted");
var number = div.find("."+type);
number.html(parseInt(number.html())+(type == "positive" ? 1 : -1));
$('#message').html('<div id="alertFadeOut" style="color: green">Your vote is added!</div>');
$('#alertFadeOut').fadeOut(3000, function () {
$('#alertFadeOut').text('');
});
},
error: function() {
$('#message').text('Vote failed. Please try again.');
}
});
});
PHP process:
$check = $db->prepare("SELECT 1 FROM user_votes WHERE image_id = ? AND user_id = ?");
$check->bindValue(1, $_POST["image_id"], PDO::PARAM_INT);
$check->bindValue(2, $_SESSION["user_id"], PDO::PARAM_INT);
//or
$check = $db->prepare("SELECT 1 FROM user_votes WHERE image_id = ? AND user_ip = INET6_ATON(?)");
$check->bindValue(1, $_POST["image_id"], PDO::PARAM_INT);
$check->bindValue(2, $_SERVER["REMOTE_ADDR"], PDO::PARAM_STR);
$check->execute();
if ($check->rowCount())
die("Already voted.");
$vote = $_POST["type"] == "positive" ? 1 : 0;
$insert = $db->prepare("INSERT INTO user_votes VALUE(?, ?, ?)");
$insert->bindValue(1, $_SESSION["user_id"], PDO::PARAM_INT);
//or
$insert = $db->prepare("INSERT INTO user_votes VALUE(?, ?, INET6_ATON(?))");
$insert->bindValue(1, $_SERVER["REMOTE_ADDR"], PDO::PARAM_STR);
$insert->bindValue(2, $_POST["image_id"], PDO::PARAM_INT);
$insert->bindValue(3, $vote, PDO::PARAM_INT);
$insert->execute();
$row = $vote == 1 ? "positive" : "negative";
$update = $db->prepare("UPDATE images SET ".$row." = ".$row." + 1 WHERE id = ?");
$update->bindValue(1, $POST["image_id"], PDO::PARAM_INT);

AJAX/Jquery not deleting row from MySQL table

I am trying to use AJAX and jQuery to delete a record from a table. The row is being removed from the page view as required, but not from the table.
Im using the following files and related sections:
Query
$result = mysql_query("SELECT id,name FROM myTable");
Query result:
while($row = mysql_fetch_array($result))
{
$id1=$row['id'];
$dataname=$row['name'];
?>
<div class="show">
<span class="name"><?php echo $dataname; ?></span><br><span class="name"><?php echo $id1; ?></span>
<span class="action">Delete</span>
</div>
<?php
}
?>
AJAX Script
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
delete.php
<?php
include('db.php');
if($_POST['id'])
{
$id=mysql_real_escape_string($_POST['id']);
$delete = "DELETE FROM `testdb` WHERE id = '$id1' ";
mysql_query($delete);
}
?>
$id=mysql_real_escape_string($_POST['id']);
$delete = "DELETE FROM `testdb` WHERE id = '$id1' ";
You are using $id1 in the delete statement, it should be $id
$delete = "DELETE FROM `testdb` WHERE id = '$id'";
NOTE : Your code is vulnerable to sql injection, start using
preparedStatement with mysqli_ or PDO
UPDATE: Using PDO to do the delete operation
error_reporting(E_ALL);
ini_set('display_errors', '1');
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', '****', '****');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$id = $_POST['id'] ;
$sql = "DELETE FROM testdb WHERE id = :id ";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

Categories