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

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.

Related

php - How to keep image buttons state after refresh

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">

using ajax to get further mysql data using data already retrieved fro database

I'm trying to build a product catalog where clients can select a product and be presented with product specifications and price. now the first thing i do is query all the products in the database omnicon_prod. from there i build an unordered list of items like such
$query = "SELECT name, id, price, image, cost_per FROM products";
$result = mysqli_query($db_connect,$query);
while($row = mysqli_fetch_assoc($result)) {
echo '<li class="product" style="list-style:none;margin-left:10px;margin-right:10px; width:150px;float:left;" id="'.$row['id'].'">
<img class="productImage" style="background-color:#f2f2f2;width:150px;padding:10px;float:left;" src="'.$row['image'].'main-image.jpg">
<div class="productText" style="width:100%;text-align:center;">
<div class="price" style="color:#fca204;font-weight:500;font-size:20px;font-family: "Conv_Geogtq-Th", sans-serif;">'.$row['price'].' <span style="color:#959595; font-size:14px; font-weight:100;">/'.$row['cost_per'].'</span>
</div>
<div class="name" style="color:#959595;font-weight:100;font-size:14px;font-family: "Conv_Geogtq-Th", sans-serif;">'.$row['name'].'
</div>
</div>
</li>';
}
What i would like to do now is attach an anchor to each list item and should the client select an item that comes from the database they would be presented with further information such as the description etc. now i know this should be done with ajax but i'm not sure how as i am relatively new to it. I would like to trigger the ajax possibly by using the onClick even on an ancho tag. this is what i have tried thus far.
the ajax
function ajaxfunction(productID)
{
$.ajax({
url: 'php-includes/products.php?productID=' + productID,
success: function(data) {
$("#productSpec").html(data);
}
});
}
the products.php page
<?php
include_once "connect.php";
$query = "SELECT name, price, image, cost_per FROM products WHERE `id` = ". mysqli_real_escape_string($_GET["ProductID"]);
$result = mysqli_query($db_connect,$query);
while($row = mysqli_fetch_assoc($result)) {
//the content from the database that matches the id of the selected item
}
?>
please can someone help me with regards to where i'm going wrong and if it's wise to use an anchor tag to trigger this event. I basically adopted and tried to incorporate the dynamic multi-level select form option into one that uses a list to grab data...
For the ajax call you can check out these pages here and here
Basically you add the data you want to send (object or string) as a parameter.
Thanks Ruben i managed to figure it out hehe. i'd like to share the final result. if there are any errors or security risks please advise me as to how i could improve the code...
The Quote.php exerpt
<?php
include_once "php_includes/connect.php";
$query = "SELECT name, id, price, image, cost_per FROM products";
$result = mysqli_query($db_connect,$query);
while($row = mysqli_fetch_assoc($result)) {
echo '<li class="product" style="list-style:none;margin-left:10px;margin-right:10px; width:150px;float:left;" id="'.$row['id'].'">
<img class="productImage" style="background-color:#f2f2f2;width:150px;padding:10px;float:left;" src="'.$row['image'].'main-image.jpg">
<div class="productText" style="width:100%;text-align:center;">
<div class="price" style="color:#fca204;font-weight:500;font-size:20px;font-family: "Conv_Geogtq-Th", sans-serif;">'.$row['price'].' <span style="color:#959595; font-size:14px; font-weight:100;">/'.$row['cost_per'].'</span>
</div>
<div class="name" style="color:#959595;font-weight:100;font-size:14px;font-family: "Conv_Geogtq-Th", sans-serif;">'.$row['name'].'
</div>
</div>
</li>';
}
?>
THE AJAX SCRIPT
<script>
$(".product").on('click',function(){
the_id = $(this).attr('id');
$.ajax({
type: "POST",
url: "php_includes/productspec.php?id=" + the_id,
success: function(data){
$("#productSpec").html(data);
}
});
});
</script>
THE productspec.php PAGE
<?php
include_once "connect.php";
$productid = mysqli_real_escape_string($db_connect, $_GET['id']);
$query = "SELECT * FROM products WHERE `id` = " . $productid;
$result = mysqli_query($db_connect,$query);
while($row = mysqli_fetch_assoc($result)) {
echo '<p>'.$row['id'].'</p>'; //just a test result i'd like to receive
echo '<p>'.$row['name'].'</p>'; //just a test result i'd like to receive
echo '<p>'.$row['price'].'</p>'; //just a test result i'd like to receive
}
?>
thanks so much Ruben. I really appreciate the help you've given me and that you provided the tools to help me figure it out myself. I don't think i'll ever forget how to do this again hahaha. i'll mark your previous post as the answer!

jQuery UI Sortable and updating a mysql database

I am doing something wrong and it's driving me nuts because I can't figure it out.
Using jQuery ui sortable to sort the divs on my page. The sorting part works kinda but it does not update the database.
The only thing I can think of is the clear within page, but if I put this on the div it acts not as fluent.
PHP
<div id="page">
<div id="listItem_'.$id.'" class="a bunch of random classes">
<div class="handle"></div>
</div>
<div id="listItem_'.$id.'" class="this one has some other classes">
<div class="handle"></div>
</div>
<div class="clear"></div>
<div id="listItem_'.$id.'" class="a bunch of some other">
<div class="handle"></div>
</div>
</div>
Javascript
$(document).ready(function(){
$("#page").sortable({
handle : '.handle',
update : function () {
var order = $('#page').sortable('serialize');
$(document).load("sort.php?"+order);
}
});
});
sort.php
<?php
session_start();
require('connect.php');
if($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_SESSION['USERNAME'])){
$i=1;
foreach ($_GET['listItem'] as $position => $item){
$sql = "UPDATE table SET position = ".$i." WHERE id = ".$item;
$res = mysql_query($sql);
$i++;
}
}
?>
Start debugging by placing var_dump('got here'); (or one of the variables) in your PHP script. Use the console in Firebug (which is an add-on) in Firefox to view the output. Step through until you find the spot where it's failing.
should $i be replaced with $position:
$sql = "UPDATE table SET position = ".$i." WHERE id = ".$item;
$sql = "UPDATE table SET position = ".$position." WHERE id = ".$item;
in any case ... if it doesnt update the database presumably you get an error?
and, i assume your table isnt actually called 'table' otherwise you should probably backtick it..

refresh single select box on click with jquery

I've a select populated by a php query, that loads the nicknames of the users logged in a specific div, called “UserList”.
<div id=”UserList” name=”UserList”>
</div>
This select is placed in a php page, “userlist.php”, loaded by jquery. The php query works fine, so I've avoided writing here the db connection.
<select name="User" id=”User”>
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result)) {
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result); ?>
</select>
My problem is that I need to reload only the select and refreshing it when a user clicks the select itself, so new users that enter the page are added by the php query and those that changed page are removed from the list. But whit every event that I tried the jquery loops, instead of activating the reload only once every time a user clicks the form and the first click event not even reload properly the php query.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#UserList").load('userlist.php');
$("#UserList").click(function() {
$("#UserList").load('userlist.php');
evt.preventDefault();
});
});
</script>
Thanks for your help.
I would suggest using AJAX to do this. AJAX allows you to query the web-server with out refreshing the entire page. This example
seems like almost exactly what you want to do.
Edit:
Put this inside your template:
<div id=”UserList” name=”UserList”>
<select name="User" id=”User”>
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result))
{
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result);
?>
</select>
</div>
Then Change the Javascript
<script type="text/javascript">
$(document).ready(function() {
$("#User").click(function() {
$("#User").load('userlist.php');
});
});
</script>
And finally change the userlist.php file:
<?
$MySql = "SELECT Name FROM Users WHERE Loc = '$Loc' ORDER BY Name";
$Result = mysql_query($MySql);
while ($rs = mysql_fetch_array($Result)) {
echo '<option value="'.$rs['Name'].'">'.htmlspecialchars($rs['Name']).'</option>';
}
$rs->close;
mysql_free_result($Result); ?>

jQuery forms.js with multiple forms per page

I would like to submit information to a mySql database using php and ajax.
The page that the info is being sent from (form.php) has multiple forms that are generated from a "while()" loop.
On success, I would a response to update a div above the particular form from which the data was submitted.
I am currently using jQuery and the jquery form plugin.
I have been successful in getting the data to the database, however I am having trouble with the response being sent back to the proper div. I have been successful in getting a response back to a div that is outside of the while() loop. I have not, however, been successful in getting a response back to a div within the loop. I have placed in the code below a div called:
">
Where I would like the note to be placed.
I know that this has everything to do with my javascript function:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('form').ajaxForm({
target: '#noteReturn',
success: function() { $('#noteReturn').fadeIn('slow'); }
});
});
</script>
The #noteReturn function does not specify which businesses div it should be placed in.
I hope that this makes sense.
Thank you for your help.
The code is below:
<!-- the form.php page -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/forms.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('form').ajaxForm({
target: '#noteReturn',
success: function() {
$('#noteReturn').fadeIn('slow'); }
});
});
</script>
<?php
$query = mysql_query("SELECT * FROM businesses");
while( $row = mysql_fetch_assoc( $query ) ):
$b_id = $row['bid'];
?>
<div class='notes'>
<?php
// query the db for notes associated with business... return notes texts and notes dates
$notesQuery = mysql_query("SELECT business_id, notes, messageDate FROM notes WHERE notes.business_id = $b_id ORDER BY messageDate");
while( $NoteRow = mysql_fetch_assoc( $notesQuery ) ) {
extract($NoteRow);
echo "$notes<br/><span class='noteDate'>$messageDate</span><br />";
} // end while$notesQuery
?>
<!-- this is where i would like jQuery to return the new note -->
<div id="noteReturn<?php echo $b_id; ?>"></div>
<!-- begin note form -->
<form name="noteForm" action="notesProcess.php" method="post">
<input type="text" name="note" />
<input type="hidden" value="<?php echo $b_id ?>" name="bid" />
<input type="submit" class="button" value="Send" />
</form>
</div> <!-- end div.notes -->
<?php
endwhile;
?>
<!-- /////////////////////////////////////////////////////
The page that the form submits to is this (notesProcess.php):
///////////////////////////////////////////////////// -->
<?php
$note = $_POST['note'];
$id = $_POST['bid'];
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if( $result ) {
echo " $note"; }
?>
Change this code:
jQuery('form').ajaxForm({
target: '#noteReturn',
success: function() {
$('#noteReturn').fadeIn('slow');
}
});
To this:
jQuery('form').ajaxForm({
target: '#noteReturn',
dataType: 'json',
success: function(data) {
$('#noteReturn' + data.id).html(data.note).fadeIn('slow');
}
});
And this code:
<?php
$note = $_POST['note'];
$id = $_POST['bid'];
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if($result) {
echo " $note";
}
?>
To this:
<?php
$note = mysql_real_escape_string($_POST['note']);
$id = mysql_real_escape_string($_POST['bid']);
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if($result) {
print json_encode(array("id" => $id, "note" => $note));
}
?>
What happened?
The change to the PHP code is making use of PHP's json_encode function to print out the id of the business to which the note was added as well as the actual note text. In the javascript code, I added the dataType of 'json' to tell the script what format of response to expect. Once the request is received in the success callback, the data variable is an object with the values we passed through json_encode. So data.id has the business id and data.note has the new note. Using jQuery's html() manipulation function, the inner html of the div is updated to the latest note. The div selector uses the id we passed, so we can update the corresponding div.
Also, this is slightly off topic, but make sure you always use mysql_real_escape_string when putting values into a query like you are. If you do not use this, your queries will be vulnerable and susceptible to injection attacks, and they are not pretty. If a customer decided to enter a note value of ');DROP TABLE businesses; you'd really feel the pain. Preferably, switch to PDO or MySQLi and use prepared statements, as they are the 'correct' way of doing queries nowadays.

Categories