how to update number without reloading - php

I am working on a voting system in jquery. I have it where a user can vote up or if they change their mind vote down and it deducts from the upvote and puts it in on the down vote. But my problem is I cant get both numbers to refresh when a vote is selected so it just uses the original number instead of the updated number.
Vote Page
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id=' + id;
var parent = $(this);
if (name == 'up') {
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
} else {
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
}
return false;
});
});
</script>
<?php
$sql=mysql_query("SELECT * FROM uploads LIMIT 9");
while($row=mysql_fetch_array($sql))
{
$msg=$row['title'];
$mes_id=$row['id'];
$up=$row['up'];
$down=$row['down'];
?>
<a href="" class="vote" id="
<?php echo $mes_id; ?>" name="up">
<?php echo $up; ?> up
</a>
<div class='down'>
<a href="" class="vote" id="
<?php echo $mes_id; ?>" name="down">
<?php echo $down; ?>
</a>
</div>
<div class='box2' >
<?php echo $msg; ?>
</div>undefined</div>undefined
<?php } ?>
The up_vote.php page..
(down_vote.php is exactly the same as up_vote except it just changes up to down.)
<?php
include("config.php");
$ip = $_SERVER['REMOTE_ADDR'];
if ($_POST['id']) {
$id = $_POST['id'];
$id = mysql_escape_String($id);
//Verify IP address in Voting_IP table
$ip_sql = mysql_query("select ip from votes where img_id='$id' and ip='$ip'");
$count = mysql_num_rows($ip_sql);
if ($count == 0) {
// Update Vote.
$sql = "UPDATE uploads SET up=up+1 WHERE id='$id'";
mysql_query($sql);
// Insert IP address and Message Id in Voting_IP table.
$sql_in = "insert into votes (id,img_id,ip,type) values ('','$id','$ip','up')";
mysql_query($sql_in);
} else {
//if already voted change it..
$result = mysql_query("SELECT * FROM votes WHERE img_id='$id' AND ip='$ip'");
while ($row = mysql_fetch_array($result)) {
$vote_type = $row['type'];
}
if ($vote_type == 'down') {
$up = mysql_query("UPDATE uploads SET up=up+1 WHERE id='$id'");
$down = mysql_query("UPDATE uploads SET down=down-1 WHERE id='$id'");
$vote = mysql_query("UPDATE votes SET type=up WHERE img_id='$id' AND ip='$ip'");
}
}
$result = mysql_query("select up from uploads where id='$id'");
$row = mysql_fetch_array($result);
$up_value = $row['up'];
echo $up_value;
}
?>

Not an answer but too long for a comment. This script:
while ($row = mysql_fetch_array($result)) {
$vote_type = $row['type'];
}
if ($vote_type == 'down') {
/* ... */
}
I don't think you need it like it is now. You are actually only using the last fetched row, not all of them. If that's your intention (because there's only one), then you don't need the while() at all. You could change it for:
$row = mysql_fetch_row($result);
$vote_type = $row['type'];
if ($vote_type == 'down') {
/* ... */
}
Furthermore, I'd recommend to change your code to PDO. It's more secure and mysql_* is deprecated.

Related

Edit multiple values in ajax

I am trying to edit two columns using ajax and php.My code currently edits one values(name) in my table and saves it to my database.When i add the second variable (p) my ajax call it updates both columns p and y with the same value.How do i edit the third value and assign it a different value from y.I want the two different columns to have different values in my db(columns:name and capacity)
This code edits and updates two values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And this is what i tried to edit three values:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$(document).on('click','.editable-submit',function(){
var x = $(this).closest('td').children('span').attr('id');
var y = $('.input-sm').val();
var p = $('.input-sm').val();
var z = $(this).closest('td').children('span');
$.ajax({
url: "process.php?id="+x+"&data="+y+"&capacity="+y,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);
$(z).html(p);}
if(s == 'error') {
alert('Error Processing your Request!');}
},
error: function(e){
alert('Error Processing your Request!!');
}
});
});
});
</script>
And heres my php file(process.php)
<?php
include("connect.php");
if
($_GET['id'],$_GET['capacity'] and $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$data' where id='$id'")){
echo "success";
}
else{
echo 'failed';
}
}
?>
And my table in index.php
<tbody>
<?php
$query = mysqli_query($con,"select * from mytable");
$i=0;
while($fetch = mysqli_fetch_array($query))
{
if($i%2==0) $class = 'even'; else $class = 'odd';
echo'<tr class="'.$class.'">
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['name'].'</span></td>
<td><span class= "xedit external-event bg-brown" id="'.$fetch['id'].'">'.$fetch['capacity'].'</span></td>
</tr>';
}
?>
</tbody>
1) your just typo error : capacity=$data look this line and change it to capacity=$capacity :
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
2) And take look in If condition too .finally your code should be like this .
<?php
include("connect.php");
if($_GET['id'] && $_GET['capacity'] && $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
if(mysqli_query($con,"update mytable set name='$data',capacity='$capacity' where id='$id'"))
{
echo "success";
}
else
{
echo 'failed';
}
}
?>
You have error in your sql query. As you not passing correct parameters.
Please see below code.
$id = $_GET['id'];
$data = $_GET['data'];
$capacity = $_GET['capacity'];
// Check Sql
$query = "update mytable set name='$data',capacity='$capacity' where id='$id'";
if(mysqli_query($con,$query)){
echo "success";
} else{
echo 'failed';
}

Managing users view profiles system and passing the id to view profile page to display correct avatar image

Im trying to set up user environment system. I have home.php page which is a profile page and planet_search.php which displays all users with ability to view their profiles. I'm struggling on passing the id variable to home.php, so I can show correct avatar image.Here the part of home.php that displays avatar image:
<img class='ima'src="<?php
$id = $_SESSION['id'];
$query = "SELECT avatar_url FROM users WHERE id = '$id' LIMIT 1";
if(isset($_POST['id'])){$idu = $_POST['id'];
"SELECT avatar_url FROM users WHERE id = '$idu' LIMIT 1";}
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_assoc($result);
if(!$row["avatar_url"]){echo 'img/profile3.png';}else{echo $row["avatar_url"];}
?>" alt="face" >
And here is JQuery from planet_search.php:
$(document).ready(function() {
$('.square').on('click', function(){
$this_id = $(this).find('.id_user').text();
$.ajax({
type: "POST",
url: "home.php",
data: { id: $this_id }, // or the string: 'id=1'
complete:
function () {
window.location = "home.php";
}
});
})
});
BUt it doesnt work? it doesnt pass the variable because the
if(isset($_POST['id']))
is never true. What am I doing wrong?
Try to use this code instead.
<?php
$idu = null;
if (isset($_GET['id'])) {
$idu = $_GET['id'];
} elseif (isset($_SESSION['id'])) {
$idu = $_SESSION['id'];
}
$avatar_url = "img/profile3.png";
if (!is_null($idu)) {
$query = "SELECT avatar_url FROM users WHERE id = '$idu' LIMIT 1";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
if ($row["avatar_url"]) {
$avatar_url = $row["avatar_url"];
}
}
?>
<img class='ima' src="<?php echo $avatar_url; ?>" alt="face">
and JS:
$('.square').on('click', function () {
$this_id = $(this).find('.id_user').text();
if ($this_id != "") {
window.location = "home.php?id=" + $this_id;
}
});
you didn't start a session, session_start();

Ajax change icon color add/remove wishlist

Example :
If user has already added product A in wishlist heart icon should be display in red color, And If user click on add to wishlist button it will remove product A from wishlist and heart icon should be display in grey color.
<a class='addtowishlist' href='javascript:;' data-data='".$row['p_id']."'><i class='fa fa-heart'></i> Add to Wish list</a>
ajax
<script type="text/javascript">
$(document).ready(function(){
$(".addtowishlist").live('click', function(evt) {
var link_data = $(this).data('data');
$.ajax({
type: "POST",
url: 'addtowishlist.php',
data: ({product_id: link_data}),
success: function(data) {
}
});
});
});
</script>
addtowishlist.php
<?php
session_start();
include 'connect.php';
if(isset($_POST['product_id'])) {
$addmemberid = $_SESSION['member_id'];
$addproductid = $_POST['product_id'];
$result = mysql_query("SELECT count(w_p_id) cnt FROM wishlist WHERE w_m_id = '$addmemberid' AND w_p_id = '$addproductid'") or die(mysql_error());
$countid = mysql_fetch_assoc($result);
if($countid['cnt'] == 1){
mysql_query("DELETE FROM wishlist WHERE w_p_id = '$addproductid' AND w_m_id = '$addmemberid'") or die(mysql_error()); // If product has already added to wishlist then remove from Database
} else {
mysql_query("INSERT INTO wishlist SET w_p_id = '$addproductid', w_m_id = '$addmemberid'") or die(mysql_error()); // If product has not in wishlist then add to Database
}
}
?>
Add a class to your heart icon.
<i class='fa fa-heart whishstate'>
Change your addtowishlist.php to something like that:
<?php
session_start();
include 'connect.php';
if(isset($_POST['product_id'])) {
$addmemberid = $_SESSION['member_id'];
$addproductid = $_POST['product_id'];
$result = mysql_query("SELECT count(w_p_id) cnt FROM wishlist WHERE w_m_id = '$addmemberid' AND w_p_id = '$addproductid'") or die(mysql_error());
$countid = mysql_fetch_assoc($result);
if($countid['cnt'] == 1){
mysql_query("DELETE FROM wishlist WHERE w_p_id = '$addproductid' AND w_m_id = '$addmemberid'") or die(mysql_error()); // If product has already added to wishlist then remove from Database
echo '0';
} else {
mysql_query("INSERT INTO wishlist SET w_p_id = '$addproductid', w_m_id = '$addmemberid'") or die(mysql_error()); // If product has not in wishlist then add to Database
echo '1';
}
}
?>
Then in change your ajax call to something like that:
<script type="text/javascript">
$(document).ready(function(){
$(".addtowishlist").live('click', function(evt) {
var link_data = $(this).data('data');
$.ajax({
type: "POST",
url: 'addtowishlist.php',
data: ({product_id: link_data}),
success: function(data) {
if(data == '1')
{
$('a[data-data="' + link_data + '"] > i.whishstate').css({"color":"red"})
}
else{
$('a[data-data="' + link_data + '"] > i.whishstate').css({"color":"red"})
}
}
});
});
});
</script>
$(".addtowishlist").live('click', function(evt) {
Change this to
$(".addtowishlist").on('click', function(evt) {

Voting system with jQuery, Ajax and PHP works only local server

I am a no good in PHP (just learning).
I tried modifying a php voting script which I downloaded from a free source. i can add image though (it was not an easy task for me and I am not done yet).
Now Voting works fine on my local server , but online it doesn't. If I click to vote, the numbers just disappear without return. below are the codes to look into.
index.php ---
<?php include('config.php');
$sql=mysql_query("SELECT * FROM messages ORDER BY `messages`.`up` DESC LIMIT 20");
while($row=mysql_fetch_array($sql)) { $title=$row['title']; $desc=$row['desc'];
$mes_id=$row['mes_id']; $image=$row['image']; $up=$row['up'];
$down=$row['down']; ?> <div id="vote"> <div class="box1">
<div class='up'><a href="" class="vote" id="<?php echo $mes_id; ?>" name="up">
<?php echo $up; ?></a></div>
<div class='down'><a href="" class="vote" id="<?php echo $mes_id; ?>" name="down">
<?php echo $down; ?></a></div></div>
<div class='image' ><?php echo "<img src=user/admin/".$image ." width='87%' height='70%'/>"?></div>
<div class ='title'><?php echo $title; ?></div>
<div class='box2' >
<?php echo $desc; ?> </div> </div>
<?php } ?>
up_vote.php --------------------------
<?php include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id']) { $id=$_POST['id']; $id = mysql_real_escape_String($id); $ip_sql=mysql_query("SELECT ip_add FROM voting_ip WHERE mes_id_fk='$id' AND ip_add='$ip'");
$count=mysql_num_rows($ip_sql)or die(mysql_error());
if($count<=20)
{
$sql = "UPDATE messages SET up=up+1 WHERE mes_id='$id'"; mysql_query( $up);
$sql_in = "INSERT INTO messages (mes_id_fk,ip_add) VALUES ('$id','$ip')"; mysql_query( $sql_in);
} else
{ echo "<script>alert('You have already voted');</script>"; }
$result=mysql_query("SELECT up FROM messages WHERE mes_id='$id'");
$row=mysql_fetch_array($result); $up_value=$row['up']; echo $up_value; } ?>
down_vote.php -----------------------------
<?php include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id']) { $id=$_POST['id'];
$id = mysql_real_escape_String($id);
$ip_sql=mysql_query("SELECT ip_add FROM voting_ip WHERE mes_id_fk='$id' AND ip_add='$ip'");
$count=mysql_num_rows($ip_sql) or die(mysql_error());
if($count<=0)
{ $sql = "UPDATE Messages SET down=down+1 WHERE mes_id='$id'"; mysql_query( $sql);
$sql_in = "INSERT INTO voting_ip (mes_id_fk,ip_add) values ('$id','$ip')"; mysql_query( $sql_in);
} else { echo "<script>alert('You have already voted');</script>"; }
$result=mysql_query("SELECT down FROM Messages WHERE mes_id='$id'");
$row=mysql_fetch_array($result);
$down_value=$row['down']; echo $down_value; }
?>
Javascript --------------------------- (this is at the index header with some HTML codes)
<script type="text/javascript">
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
$(this).fadeIn(200).html('<img src="dot.gif" align="absmiddle">');
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
} });
}
else
{
$(this).fadeIn(200).html('<img src="dot.gif" align="absmiddle">');
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
</script>
I appreciate anyone helping out, thanks everyone.
From your code,
if($count==50)
then only the values are being updated!!. How is it possible for a person who is going to vote for the first time???
It should be
if($count<50)
Going to take a wild stab here but 9/10 'It works locally but not on live' issues are either php version mismatches or differences in Apache config (differing module configurations etc) presuming LAMP.
Check the php versions match and if they don't check the change logs to detect any functions that do not work within both. This is likely the issue.
And as commented above. Always check your server logs.

jquery function only working once?

I have this function that is suppose to change the html of a span. It works the first time but anyclick after that it doesn't change anything. I know the query is working because the database is updating. Here's the code.
$('#availabilityicon').click(function() {
$.ajax({
type: "GET",
url: "includes/changeavailability.php",
success: function(msg) {
if(msg === "available") {
var vailspan = $('span#avail').html('<a id="availabilityicon" href="#"><img align="center" width="16px" height="16px" src="images/available.png" /></a>');
}
else if(msg === "unavailable") {
var availspan = $('span#avail').html('<a id="availabilityicon" href="#"><img align="center" width="16px" height="16px" src="images/unavailable.png" /></a>');
}
}
});
});
here is the php code
<?php
session_start();
$user = $_SESSION['username'];
include("dbcon.php");
$result = mysql_query("SELECT availability FROM user WHERE username='$user' ORDER BY id DESC") or die(mysql_error());
$row = mysql_fetch_assoc($result);
$availability = $row['availability'];
if($availability == 'yes') {
$query = mysql_query("UPDATE user SET availability='no' WHERE username='$user'") or die(mysql_error());
echo "unavailable";
}
elseif($availability == 'no' or $availability == "") {
$query = mysql_query("UPDATE user SET availability='yes' WHERE username='$user'") or die(mysql_error());
echo "available";
}
mysql_close($con);
?>
There's a spelling mistake in your javascript, you've put vailspan where you probably meant to put availspan after the if(msg === "available") { line.
If it's not that, try changing the click event to a live one:
$('#availabilityicon').live('click', function() {
just in case your javascript is overwriting that the #availabilityicon icon element and failing to re-attach the event to the new one
The "availabiltyicon" you click is being replaced with another with the same name. You can try using .live() or you can read up on event delegation.

Categories