php - How to keep image buttons state after refresh - php

I am having a problem keeping the state of some image buttons after refresh or log out. I have a favourite button on each article on page that a user can click to favourite it. I use the following jquery function to send the unique id of the post to a mysql table:
$('.faver').on('click',function() {
var articleId = $(this).closest('.row').attr('id');
$.ajax(
{
url: "favscript/addremove",
method: "POST",
data: { favourite: articleId },
success: function()
{
alert(<?php echo $favid ?>);
}
});
});
then in the recieving php file i get the session variable like this:
session_start();
if(isset($_SESSION['id']) AND isset($_POST['favourite'])){
$user = mysql_real_escape_string($_SESSION['id']);
$_SESSION['favourite'] = $_POST['favourite'];
$favid = mysql_real_escape_string($_SESSION['favourite']);
and then I insert values into mysql table like so:
// Firstly, check if article is favourite or not
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE user=$user AND favid=$favid");
$matches = mysql_num_rows($query);
// If it is not favourited, add as favourite
if($matches == '0'){
mysql_query("INSERT INTO ajaxfavourites (user, favid) VALUES ('$user', '$favid')");
}
// Instead, if it is favourited, then remove from favourites
if($matches != '0'){
mysql_query("DELETE FROM ajaxfavourites WHERE user=$user AND favid=$favid");
}
}
Now all of the above is working but my problem is that I can't seem to figure out a way for each button to remember its state once the user refreshes or logs out. if I set $favid to $_SESSION['favourite'] it will just set the button state the same for all buttons after refresh.
this is how i check what the button state should be:
<!--Favourite Button-->
<div id="favouritediv">
<?php
$user = $_SESSION['id'];
$favid = $_SESSION['favourite']; // <- problem here
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE user=$user AND favid=$favid");
$matches = mysql_num_rows($query);
if($matches == 0){
?>
<img id="button" class="faver fave0 tog" src= "favscript/images/0.jpg" onclick="" width="54" height="49">
<?php
}
if ($matches == 1) {
?>
<img id="button" class="faver fave0 tog" src= "favscript/images/1.jpg" onclick="" width="54" height="49">
<?php
}
?>
</div>
<!--Favourite Button END-->
if i set $favid to the id of the article directly like: $favid = 3; it will work perfect but I can't get my head around how to do it properly with a $session variable or something that will get the article id for each button separately and only effect each button by itself.
I hope this makes sense, I am new to php and any help on how I should do this will be much appreciated.
thanks.

If you want sessions even after user logged out , simply Store login activities in separate table. like columns User ID and Session IDs. finally get the last row of the activity table.
Happy coding !

I think your query should be to fetch all the favids for a user:
$query = mysql_query("SELECT favid FROM ajaxfavourites WHERE user=$user");
while($row = mysql_fetch_assoc($result)){
$allFavIds[] = $row['favid'];
}
Now using $allFavIds array you can check for each button if its "favid" exists in this array.
<img id="button" class="faver fave0 tog" src="favscript/images/<?php echo in_array($individualFavId, $allFavIds) ? '1.jpg' : '0.jpg' ; ?>" onclick="" width="54" height="49">
Of-course the $individualFavId will be replaced by your individual favids.
Sample Code:
<img id="button" class="faver fave0 tog" src="favscript/images/<?php echo in_array(3, $allFavIds) ? '1.jpg' : '0.jpg' ; ?>" onclick="" width="54" height="49">

Related

How do I implement a like counter using PHP, jQuery and AJAX?

I am working on creating a like counter for quotes. I am trying to increment the like counter when the user clicks on the like button and display the number of likes.
Problems I encountered:
Like counter gets incremented when I refresh the page (Not because I am actually hit the like button).
I tried implementing jQuery for the updation of the like counter in real time but failed :(
I referred to all the QnA related to this couldn't find the desired solution. I went through this [question]PHP/MySQL Like Button, and made the necessary changes but now there is no updation in the database when I click the button.
This is the code for one quote.
<div class="testimonial text-sm is-revealing">
<div class="testimonial-inner">
<div class="testimonial-main">
<div class="testimonial-body">
<p id="q1">
<?php
$sql = "select quotes from voted where voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?></p>
</div>
</div>
<div class="testimonial-footer">
<div class="testimonial-name">
<button method="POST" action='' name="like" type="submit" class="like"><b>Like</b></button>
<?php
if(isset($_POST['like'])){
$link = mysqli_connect("localhost","root","","success");
$sql = "UPDATE voted SET likes = likes+1 WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
}
?>
<label>
<?php
$link = mysqli_connect("localhost","root","","success");
$sql = "SELECT likes from voted WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?>
</label>
<button class="btn" id="clipboard" onclick="copyFunction('#q1')"></button>
</div>
</div>
</div>
How do I make the like counter implement when I click on the like button?
How do I implement jQuery and AJAX to this, so that the counter is updated without a page refresh?
Please pardon my poor code structure.
Thanks for any help.
P.S This how a single quote will look like
You need three things for an asynchronous setup like this to work:
Your back-end script to handle ajax requests
Your front-end page
Your JQuery script to send ajax requests and receive data
Your back-end PHP script would look something like this (async.php):
<?php
if(isset($_POST['get_quotes'])) {
$sql = "select quotes from voted where voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
}
if(isset($_POST['like'])) {
$link = mysqli_connect("localhost","root","","success");
$sql = "UPDATE voted SET likes = likes+1 WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
}
?>
Your front-end page will include an element with an ID to hook onto with the JQuery, and a button with a class or ID to capture the click event (page.html):
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="core.js"></script>
<body>
<button id="increment-like" value="Like" type="button" />
<p id="like-count">
</p>
</body>
<html>
Finally, your JavaScript file should look something like this, for a basic ajax request using JQuery (core.js):
$(document).ready(function() {
// initially grab the database value and present it to the view
$('#like-count').text(getDatabaseValue());
$('#increment-like').on('click', function() {
incrementDatabaseValue();
});
});
function getDatabaseValue() {
$.post("async.php",
{
get_quotes: true
},
function (data, status) {
// check status here
//return value
return data;
});
}
function incrementDatabaseValue() {
$.post("async.php",
{
like: true
},
function (data, status) {
// check status here
// update view
$('#like-count').text(getDatabaseValue());
});
}
I haven't tested this code but it should be clear and detailed enough to get you on the right track.

update database with checkbox

My database table has 2 fields: id (int) and state (enum -> 0,1).
What I need to do is to update my database (my state field) with the state of a checkbox (0 for empty, 1 for checked).
To show each of the fields in my database, I use a loop:
Loop:
<?php
foreach ( $posts_array as $module )
{
?>
<h2><?php echo $module->titre; ?></h2>
<input type="checkbox" name="chkbx_<?php echo $module->id; ?>"> id="chkbx_<?php echo $module->id; ?>" class="onoffswitch-checkbox"> On/Off <br />
<?php
}
?>
My update file:
foreach ($_GET['onoffswitch-checkbox'] as $id => $state)
{
// $_GET['onoffswitch-checkbox'] = class for all my checkboxed
// $id = my database row id
// $state = on/off
$query = mysql_query("UPDATE records SET id='$id' WHERE state='$state'", $conn) or die (mysql_error($conn));
$id++;
}
Where I need help is the AJAX part of the code. I'm guessing it looks something like this, but it doesn't seem to work:
AJAX
$(document).ready(function() {
$("onoffswitch-checkbox").click(function() {
var id = $(this).attr('id');
$("#state_span").load("module_update.php?"+id);
}
}
I've been looking around, seen a few examples where the we could do so with a submit button, but none where the information is automatically recorded when clicking the checkbox.
Try this:
AJAX
$(document).ready(function() {
$(".onoffswitch-checkbox").click(function() {
var id = this.id; //changed here also, just because jQuery is not needed here
var state = this.checked ? 1 : 0;
$("#state_span").load("module_update.php?id="+id+"&state="+state);
}
}
Changed 3 things:
added a dot in $("onoffswitch-checkbox") so its now $(".onoffswitch-checkbox")
added id= after module_update.php? and before id value.
since you need state also I added that also with a & to separate the values for $_GET in php to separate them
PHP
I don't know what you mean with $_GET['onoffswitch-checkbox'] in the php, maybe a mistake? My suggestion does not need it anyway, neither does your mysql query.
Since you will be only clicking one at a time I see no need for the foreach loop in php, so you could do this:
$id = $_GET['id'];
$state= $_GET['state'];
// $_GET['onoffswitch-checkbox'] ?? I don't think you need this...
// $id = my database row id
// $state = on/off
$query = mysql_query("UPDATE records SET id='$id' WHERE state='$state'", $conn) or die (mysql_error($conn));
$id++;

Creating Link For User To Delete Row

I'd like to ask two things for this particular user ability. The first is how to delete a row upon user clicking a button. The second is....would this be a good idea? How can I create a safe environment for someone to do this. This is what I've got so far :
<?php
include_once "db_conx.php";
if($_POST['wall'] == "post") {
//open if($_POST['wall'] == "post")
$id = mysqli_real_escape_string($db_conx, trim($_POST['id1']));
if($id == " ")
{
exit();
}
else
$sql = "SELECT FROM courseprogress WHERE userid='$id' LIMIT 1";
$results = mysqli_query($db_conx, $sql);
$sidebar = mysqli_num_rows($results);
if($sidebar > 0) {
//close if($sidebar > 0)
while($row = mysqli_fetch_assoc($results))
{
$sql = mysqli_query("DELETE FROM courseprogress WHERE userid='$id'");
$results = mysqli_query($db_conx, $sql);
}
//close if($sidebar > 0)
}
else
{
echo 'Already Complete!';
echo "<pre>";
var_dump($sql);
echo "</pre><br>";
}
//close if($_POST['wall'] == "post")
}
?>
Right now I'm in the process of dumping out variables, but can't seem to get my id variable right.
The idea is to "start over" in a sense. The table holds the user progression and settings. Once they've decided they need to start over they will be allowed to do so by simply deleting the row. When the begin again the row will be created again.
A little more information:
The small form script I was trying to use is:
<div class="userInfoContain"><div class="positionRight"><div id="form"> <form><div class="submit"><input type="hidden" id="id" value="'.$id.'" /><input type="submit" name="button" id="button" value="Start Over" onclick="return false" onmousedown="javascript:wall();"/><img src="images/loading.gif" alt="" width="15" height="15" id="loadingstart" /></div></form></div></div></div>
<script type="text/javascript">
$(document).ready(function(){
$('#loadingstart').hide();
});
function wall(){
$('#loadingstart').show();
var id = $('#id').val();
var URL = "./includes/start-over-user.php"; /////post.php will be equal the variable "comment"
$.post(URL,{wall:"post",id1:id},function(data){//parameter wall will be equal "post", name1 will be equal to the var "name" and comment1 will be equal to the var "comment"
$("#result").prepend(data).show();// the result will be placed above the the #result div
$('#loadingstart').hide();
});
}
</script>
1) Safely allow user to delete: The safest way is to not allow delete permissions on the MySQL user that is being used by the website. A method called soft delete is much safer for deleting rows in MySQL tables. This involves adding a column named "is_deleted" to the table where you are making this update. When is_deleted is set to 0, allow the row to act normally. When a user sets is_deleted to 1, it should act as if it doesn't exist. In this example, I am assuming you have set $is_deleted to the column is_deleted in your table:
if($is_deleted == '1')
{
// Don't display
}
else
{
// Display
}
2) How to implement: The best way to do this is with:
UPDATE tablename SET is_deleted = '1' WHERE id = '".$id."'
which should be executed through AJAX command or a link that will execute the MySQL query.
to delete I advice you to use ajax , it's perfect and you can have more control on this action
the other Problem i need more explanation i didn't understand you good

Making album-viewer like facebook

I am working on making a album-viewer like facebook.
I have made the "setup", you can see the photo, what album its in and so, now I would like to make the "next" "previous" buttons work.
I have seen them using preloading while viewing a current, and i wish to accomplish something like that.
But first of all, how can I make the "next"? What are the procedure to make the "next" work.
With this I mean how should I code it, so it knows which picture is next? I would like to sort it from the date(order by date), so the next should be newer than the current date, and previous older than the current date.
My database looks like this:
album
id uID title
album_photos
id aID uID photo date
aID holds the id of the album(album ID), uID holds the id of the user(userID).
I also want to make use of javascript too. Make an ajax request, instead of refreshing whole page.
So my question is:
What is the procedure of making next/prev button, if I would like to make it work after date DESC, how does the javascript look like? An ajax request to file.php, that are grabbing the latest image from the database and then on success it replace the current photo and show it? What about the adressbar, in facebook the adressbar changes align with loading new photo.
Any well explained answer for procedure of making this, will accept the answer
This here will load images from the database using ajax (next/previous). Also includes guides and a preloader (hosted here http://www.preloaders.net/). Let me know if you have any questions.
Here you go. these are 3 files
index.php ...display page
ajax.php ...read database for images
show.php ...loads images
just remember to set host, user, password & databasename in ajax.php
copy & paste these:
1. index.php
<?php
include("ajax.php");
?>
<script type="text/javascript" src="JQUERY/jquery.js"></script>
<script>
var ID = "<?php echo $id; ?>";
var inc = ID + 1;
var dec = ID;
var totalpages = "<?php echo $totalpages + 1; ?>";
$(function(){
$('.loader').hide();
<!-- np = next & prev button functions -->
$('.np').click(function() {
if($(this).attr('id') == "next") {
$(this).attr('push', inc++);
if($(this).attr('push')<totalpages) {
$.ajax({url:"show.php", data:"id=" + $(this).attr('push'), success: AjaxFunc, cache:false });
$('.loader').show();
dec = inc - 2;
$('#images').hide();
}
}
else if($(this).attr('id') == "prev") {
$(this).attr('push', dec--);
if($(this).attr('push')>-1) {
$.ajax({url:"show.php", data:"id=" + $(this).attr('push'), success: AjaxFunc, cache:false });
$('.loader').show();
inc = dec + 2;
$('#images').hide();
}
}
});
});
<!-- this function is called after ajax send its request -->
function AjaxFunc(return_value) {
$('#images').html(return_value);
$('.loader').hide();
$('#images').show();
}
</script>
<div id="images">
<!-- loads default numbers of images. whats inside here will change once you click next or prev -->
<?php
for($i=$id * $limit; $i<$limit + $id * $limit; $i++) {
echo $imagearray[$i]."<br/>";
}
?>
</div>
<!-- next & previous buttons -->
<a class="np" id="prev" push="<?php echo $id; ?>" href="#">Prev</a>
<a class="np" id="next" push="<?php echo $id + 1; ?>" href="#">Next</a>
<!-- preloader. hidden on start. will show while images load -->
<img class="loader" src="http://www.preloaders.net/generator.php?image=75&speed=5&fore_color=000000&back_color=FFFFFF&size=64x64&transparency=0&reverse=0&orig_colors=0&uncacher=26.066433149389923"/>
2. ajax.php
<?php
//id is tjhe page number. it is 0 by default. while clicking next/prev, this will not change. set it like this: file?id=0
$id = $_GET['id'];
//connect to the databsae
$host="localhost";
$user = "username";
$password = "";
$database = "database_name";
$connect = mysql_connect($host, $user, $password) or die("MySQL Connection Failed");
mysql_select_db($database) or die ("Database Connection Fail");
//set your the limit of images to be displayed
$limit = 5;
//push images into array
$q = mysql_query("SELECT * FROM image_table");
$num = mysql_num_rows($q);
while($r = mysql_fetch_array($q)) {
$imagearray[] = "<img src='"
.$r['IMAGE_URL']
."'/>";
}
//will determine total number of pages based on the limit you set
$totalpages = ceil($num/$limit) - 1;
?>
3. show.php
<?php
include("ajax.php");
for($i=$id * $limit; $i<$limit + $id * $limit; $i++) {
echo $imagearray[$i]."<br/>";
}
?>
If you are sorting your photos by date DESC and you got the current photos date do the following:
To find the next photo: Order your photos by date DESC and select the first photo whos date is smaller than the date of the current photo. Fetch only the first one.
To find the prev photo: Order your photos by date ASC and select the first photo whos date is greater than the date of the current photo. Fetch only the first one.
Construct the SQL-Statements for this by yourself.

$.post() in jQuery not working

I'm making a rating system, and I have the following jQuery code on my index.php page:
<script type="text/javascript">
$(document).ready(function() {
$("[id^=rating_]").hover(function() {
var rid = $(this).attr("id").split("_")[1];
$("#rating_"+rid).children("[class^=star_]").children('img').hover(function() {
$("#rating_"+rid).children("[class^=star_]").children('img').removeClass("hover");
/* The hovered item number */
var hovered = $(this).parent().attr("class").split("_")[1];
var hovered2 = $(this).parent().attr("class").split("_")[1];
while(hovered > 0) {
$("#rating_"+rid).children(".star_"+hovered).children('img').addClass("hover");
hovered--;
}
$("#rating_"+rid).children("[class^=star_]").click(function() {
var current_star = $(this).attr("class").split("_")[1];
$.post("send.php", {rating: current_star, id: rid});
});
});
});
});
</script>
Basically theres a hover effect and then when you click on the star, it'll send a post request to send.php, with the info on the rating clicked and the id of the element. Below this script I have some PHP that looks like this:
<?php
$query = mysql_query("SELECT * FROM test");
while($row = mysql_fetch_array($query)) {
$rating = (int)$row[rating];
?>
<div id="rating_<?php echo $row[id]; ?>">
<span class="star_1"><img src="star_blank.png" alt="" <?php if($rating > 0) { echo"class='hover'"; } ?> /></span>
<span class="star_2"><img src="star_blank.png" alt="" <?php if($rating > 1.5) { echo"class='hover'"; } ?> /></span>
<span class="star_3"><img src="star_blank.png" alt="" <?php if($rating > 2.5) { echo"class='hover'"; } ?> /></span>
<span class="star_4"><img src="star_blank.png" alt="" <?php if($rating > 3.5) { echo"class='hover'"; } ?> /></span>
<span class="star_5"><img src="star_blank.png" alt="" <?php if($rating > 4.5) { echo"class='hover'"; } ?> /></span>
<div class="clearleft"> </div>
</div>
<br />
<?php
}
?>
And then of course I have some CSS to make it look nice.
The send.php file looks like this:
<?php
mysql_connect("localhost", "admin", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$rating = (int)$_POST['rating'];
$id = (int)$_POST['rid'];
$query = mysql_query("SELECT * FROM test WHERE id = '".$id."'") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
if($rating > 5 || $rating < 1) {
echo"Rating can't be below 1 or more than 5";
}
else {
$total_ratings = $row['total_ratings'];
$total_rating = $row['total_rating'];
$current_rating = $row['rating'];
$new_total_rating = $total_rating + $rating;
$new_total_ratings = $total_ratings + 1;
$new_rating = $new_total_rating / $new_total_ratings;
// Lets run the queries.
mysql_query("UPDATE test SET total_rating = '".$new_total_rating."' WHERE id = '".$id."'") or die(mysql_error());
mysql_query("UPDATE test SET rating = '".$new_rating."' WHERE id = '".$id."'") or die(mysql_error());
mysql_query("UPDATE test SET total_ratings = '".$new_total_ratings."' WHERE id = '".$id."'") or die(mysql_error());
}
}
?>
There are 3 rating columns in the database table;
total_rating: total ratings (all the ratings added together).
rating: the current rating
total_ratings: the amount of ratings.
The problem is, if I change the $_POST['rating'] and $_POST['rid'] to $_GET and put the information int he url, for instance, send.php?id=1&rating=4, it works, and the database gets updated. However, when I press the stars, the database isn't updated. After messing around with the script I realised that the post must be working, however the id returns as 0.
To test this further I put this in the click function:
document.write(current_star+rid);
To see what was returned. The problem seems to be that the number that is returned is multiplied by the amount of times I hover over elements. So if I hover over maybe, 6 of the stars, then the current_star and ID will be repeated 6 times.
I feel like I'm so close to getting this to work, has anyone got any idea what's up with it? Thanks in advance.
And important thing to realize about jQuery's event handling is that it is registry-based, meaning that jQuery allows you to register multiple callbacks for any particular event, and it will invoke them in the order in which they were bound.
The reason you're seeing repeated current_star and id values is because you keep binding more and more events on every hover. This is because have your click() call inside your hover() call, therefore every time you hover, you will bind another click() event.
Try binding your click() event outside your hover event, using something like this:
$("[id^=rating_]").children("[class^=star_]").click(function() {
var rid = $(this).parent().attr("id").split("_")[1];
var current_star = $(this).attr("class").split("_")[1];
$.post("send.php", {rating: current_star, id: rid});
});
You also probably don't want to bind one hover() call inside the other, for the same reason.
I noticed you have used $_POST['rid'] instead of $_POST['id']. May be that's your problem.

Categories