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.
Related
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.
This is my code. please add if else statement in this code. As if ads found in my database than ads display from database otherwise chitika code ads display. no this code display both ads first display ads from my database and then from chitika code ads. please add if else statement. because i have no idea how to apply if else in this matter.
<div style="margin-left:-7px ! important;">
<?php
$sql4 = "SELECT * FROM abc ORDER BY id DESC LIMIT 1";
$query4 = $conn->query($sql4);
$row4 = $query4->fetch(PDO::FETCH_ASSOC);
$link4 = $row4['link_url'];
$images4 = $row4['imagepath'];
$immg4 = basename($images4);
$imagee4 = "adverts"."/".$immg4;
$rowc = $query4->rowCount(PDO::FETCH_ASSOC);
if ($rowc>=1){
echo "
<a href='$link4'; target='_blank'><img src='$imagee4';></a>";
}
else {
echo "";
}
?>
<script type="text/javascript">
( function() {
if (window.CHITIKA === undefined) { window.CHITIKA = { 'units' : [] }; };
var unit = {"calltype":"async[2]","publisher":"seeknfameads","width":300,"height":250,"sid":"Chitika Default","color_site_link":"337ab7","color_text":"337ab7"};
var placement_id = window.CHITIKA.units.length;
window.CHITIKA.units.push(unit);
document.write('<div id="chitikaAdBlock-' + placement_id + '"></div>');
}());
</script>
<script type="text/javascript" src="//cdn.chitika.net/getads.js" async> </script>
</div>
please write code again with if else. as i copy paste into my page. thanks in advance.
It seems you are asking how if/else works in php.
if else is used to execute some code when a statement is true and another one if it is false.
If you define a function to get the number of ads from your database and a function to display the ads from your database and a function to display the ads from Chikita then your code might look like this:
if(getNumberOfAdsInMyDB() > 0){
displayAdsFromDatabase();
}
else {
displayAdsFromChikita();
}
This will only execute the function displayAdsFromDatabase() if getNumberOfAdsInMyDB() returns a value that is bigger than 0 and will only execute the function displayAdsFromChikita() when getNumberOfAdsInMyDB() returns a value that is not bigger than 0.
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">
I have creating a little section on my webpage that changes randomly everytime the webpage opens. The code looks like this.
<div id ="quote-text">
<?php
mysql_connect("localhost", "xxxxxxx", "xxxxxxx") or die(mysql_error());
mysql_select_db("xxxxxxx") or die(mysql_error());
$result = mysql_query("SELECT * FROM quotes WHERE approved=1 ORDER BY RAND () LIMIT 1")
or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
echo "<img src=http://www.xxxxxxxxxx.com/images/".$row['image'] ." width=280px ><br>";
echo '<span class="style2">'.$row['quote'].'</span class>';
echo "<tr><td><br>";
echo "<tr><td>";
}
echo "</table>";
?>
</div>
What do I need to do to make this change every 5 seconds randomly withoutrefreshing the whole page?
thank you
You will need to make an AJAX call to change content on the page without refreshing.
Check out the W3Schools tutorial here: http://www.w3schools.com/ajax/ajax_intro.asp
Or even better use the mozilla tutorial:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
I'd say the most optimized solution would be to use a solution that makes use of both PHP, and javascript/Jquery.
First off it I would avoid to make an AJAX call to a PHP script every 5 seconds..
Instead you could make one call every X number of minutes and get a set of 12X images.
I would then use javascript, with setInterval to have the client change the image.
Halfway through, you can make another call to the PHP script to add new elements to your set of images, and remove the previous.
An approach like this would reduce overhead both clientside and serverside.
Update: Below a rough implementation of this method
Javascript:
<?php
if(isset($_GET['getBanners']))
{
header('Content-Type: application/json');
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("stackoverflow2") or die(mysql_error());
$json_rows = array();
$result = mysql_query("SELECT * FROM quotes WHERE approved=1 ORDER BY RAND () LIMIT 12;")
or die(mysql_error());
$element = 0;
while($row = mysql_fetch_array( $result )) {
$json_rows[$element] = $row['image'];
$element++;
}
print '{"dataVal":'.json_encode($json_rows).'}';
return;
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script>
//alert('test1');
var randomBanners = new Array ( );
var currentBannerIndex = 0;
function readNewBanners(startElement, numElements)
{
$.getJSON('http://127.0.0.1/stackoverflow/Banner.php?getBanners=1', function(data) {
for (var i = startElement; i < data.dataVal.length && i<startElement + numElements ; i++) {
randomBanners[i] = data.dataVal[i];
}
});
}
function refreshBannerImage()
{
if(document.getElementById('banner') == undefined) return;
document.getElementById('banner').innerHTML = ("<img src='"+randomBanners[currentBannerIndex]+"'/>");
currentBannerIndex = (currentBannerIndex+1)%12;
}
$( document ).ready(function() {
readNewBanners(0, 12);
setInterval(function() {
readNewBanners(0, 12);
}, 60000);
setInterval(function() {
refreshBannerImage();
}, 500);
});
</script>
</head>
<body>
<div id="banner">
Banner Here
</div>
</body>
</html>
SQL:
create table quotes
(
image varchar(10),
approved int
);
insert into quotes values ('http://dummyimage.com/600x400/000/fff&text=1',1);
insert into quotes values ('http://dummyimage.com/600x400/000/fff&text=2',1);
insert into quotes values ('http://dummyimage.com/600x400/000/fff&text=3',1);
etc...
You need to use AJAX for that. I suggest you to use the jQuery or a similar framework. Here is a nice example of what you want How to update a specific div with ajax and jquery. Add a setInterval() call like in this post http://forum.jquery.com/topic/jquery-setinterval-function and you are done.
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.