Print like count without page refresh - php

I have a like/unlike post on my website, and when I click the like button I would like the value of check2 to show beside like without me having to refresh the page to see it. Currently I'll click like and it inserts the data but only shows on a page refresh. I'm hopeless with this kind of stuff.
Here is the code in the order it executes.
Thanks for any help.
POST LIKE
echo "<div class='stream_option'><a id='likecontext_".$streamitem_data['streamitem_id']."' style='cursor:pointer;' onClick=\"likestatus(".$streamitem_data['streamitem_id'].",this.id);\">";
if($checklikes>0){
echo "Unlike";
}else{
echo "Like";
}
echo "</a> ";
$check2 = user_core::print_like_count($streamitem_data['streamitem_id']);
if($check2>0){
echo "(".$check2.")";
}
Ajax Function
function likestatus(postid,contextid){
var obj = document.getElementById(contextid);
if(obj.innerHTML=="Like"){
obj.innerHTML="Unlike";
}else{
obj.innerHTML="Like";
}
$.post("../include/like_do.php", { streamitem_id: postid} );
}
LIKE_DO
$check = user_core::check_liked($_SESSION['id'],$_POST['streamitem_id'],1);
user_core::do_like($_SESSION['id'],$_POST['streamitem_id'],1);
if($check==0){
?>
<?php
}else{
?>
<?php
}
}
else{
echo "<script>alert('Error liking post');</script>";
}
?>
USER_CORE
function check_liked($id,$streamid,$value){
$check = "SELECT feedback_id FROM streamdata_feedback WHERE feedback_streamid=$streamid AND feedback_userid=$id AND feedback_rating=$value";
$check1 = mysql_query($check);
$check2 = mysql_num_rows($check1);
return $check2;
}
function print_like_count($streamid){
$check = "SELECT feedback_id FROM streamdata_feedback WHERE feedback_streamid=$streamid AND feedback_rating=1";
$check1 = mysql_query($check);
$check2 = mysql_num_rows($check1);
if($check2>0){
echo "(".$check2.")";
}
}

What you're looking for is an AJAX submission using DHTML to change the value of the likes.
<script language="javascript">
$(".likeButton").click(function() {
$.post("likeProcessor.php", {
id: $(this).attr('id')
}, function(data) {
$("#likeIndicator" + $(this).attr('id')).html(data);
});
</script>
Then your likeProcessor script will simply return the number of likes for that item.
NOTE: This is pseudo-code to give you an idea of what needs to happen. For further info on jQuery and Ajax, RTM at http://www.w3schools.com/jquery/default.asp and http://www.w3schools.com/ajax/default.asp respectively.

Related

Ajax + mysql reload page

i try to work on something but it's not realy working as i want, so first we have the index page with the ajax code :
function redirect(){
$(".redirect").load("redirect.php");
}
setInterval(function(){
redirect()
}, 3000);
</pre>
Of course in the body we have this :
<div class="redirect"></div>
In the redirect.php code, we have this :
<?php
session_start();
include('db.php');
$query = "SELECT * FROM db WHERE client=".$_SESSION['clientvict']."";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$redirect = $row["redirect"];
if($redirect == 1) {
//header('location: '.$_SESSION['redirect_url']);
}
}
}
Okay so, to start, when my client is on the index.php, the row redirect is on 0.
And on my web panel, i can set up the value to 1, if the value is on 1, i want the client to be redirected of the index page to my $_SESSION['redirect_url'].
But the problem is, of course, it redirect only in the class="redirect" div.
But i want him to be redirected from the index page, so i tried in the redirect.php code this :
<?php
session_start();
include('db.php');
$query = "SELECT * FROM db WHERE client=".$_SESSION['clientvict']."";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$redirect = $row["redirect"];
if($redirect == 1) {
$ok = 1;
}
}
}
And on the index.php page i added this below the class redirect div :
<?php
if($ok == 1) {
header('location: url');
}
?>
But it doesn't detect the $ok from the redirect.php.
Any idea how i could fix this problem ?
Thank !
Okay i resolved the problem, i don't know if it's the proper way to do it, but it's working as i want ! i did that :
redirect.php :
<?php
session_start();
include('db.php');
$query = "SELECT * FROM db WHERE client=".$_SESSION['ccvict']."";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$redirect = $row["redirect"];
if($redirect == 1) {
echo '<div id="content"><div id="activity">1</div></div>';
}
else {
echo '<div id="content"><div id="activity">0</div></div>';
}
}
}
And the AJAX in index.php :
<script>
$(document).ready(function() {
function redirect(){
$.ajax({
url:'redirect.php',
type:'GET',
success: function(data){
var active = $(data).find('#activity').html();
if(active == 1) {
<?php echo 'window.location.replace("'.$_SESSION['redirect_payment'].'");'; ?>
}
}
});
}
setInterval(function(){
redirect()
}, 3000);
});
</script>
Hope it will help, thank #CBroe

How to get a single mysql value and output it to an ajax call?

I'm trying to get a number from a mysql line then outputting it to ajax. the number can't be a string because I will multiply it in ajax. This is what i have so far. I'm not sure what to do from here.
ajax:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var category = $("txtCat").val();
var number = $("txtNum").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
if ( user > 0 and user < 30 ){
alert(result);
}
else{
alert( 'invalid user ID');
}
});
});
});
php:
<?php
$userID = $_GET["ID"];
$amount = $_GET["amount"];
$category = $_GET["category"];
$num = $_GET["number"];
require "../code/connection.php";
$SQL = "select userAmount from user where userID= '$userID'";
$reply = $mysqli->query($SQL);
while($row = $reply->fetch_array() )
{
}
if($mysqli->affected_rows > 0){
$msg= "query successful";
}
else{
$msg= "error " . $mysqli->error;
}
$mysqli->close();
echo $msg;
?>
Pretty straightforward - you just grab the value from the row and cast it as a float.
while($row = $result->fetch_array() )
{
$msg = floatval($row['userAmount']);
}
if($msg > 0) {
echo $msg;
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
And one small change in your ajax call:
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
You need to add echo $row['userAmount']; inside or after your while loop, and drop the second echo. You should be able to take result within your AJAX code and use it as a number directly.
Here function(query), query is the response from the AJAX call. So your alert should be:
alert(query);
result is empty.
You also should be using prepared statements and outputting the value you want.
Something like:
<?php
$userID = $_GET["ID"];
$amount= $_GET["amount"];
require "../code/connect.php";
$SQL = "SELECT userAmount FROM user WHERE userID= ?";
$reply = $mysqli->prepare($SQL);
if($mysqli->execute(array($userID))) {
$row = $reply->fetch_array();
echo $row['amount'];
}
else
{
$msg = "error" . $mysqli->error;
}
$mysqli->close();
?>
Then JS:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
});
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt to convert the value to an integer/float in JS.

Deleting an image only after the form is submitted

After a picture is uploaded I want to let the user have the option to delete it by clicking on the 'x' on the image. I tried some jquery codes that I searched online but nothing had the result I want. Is there a way to remove the image from the database only when the submit button is clicked rather than redirecting to a delete page and then having to go back to delete another image?
if($res18 && mysql_num_rows($res18) > 0){
while($row18 = mysql_fetch_assoc($res18)){
if (file_exists($row18['images']) === true){ ?>
<?php
//mysql_query("DELETE FROM `images` WHERE `images`='".$row18['images']."' AND `ad_id` = '".$id."'");
echo '<img src="'.$row18['id'].'" class="pictures">';
}
}
}
insert quesry:
mysql_query("INSERT INTO `images` ($fields) VALUES ($data)");
I assume the logic would be somewhat like this: Once the 'x' link is clicked, run a function that runs the delete query.
Any help is appreciated!
UPDATE:
$res18 = mysql_query("SELECT * FROM `images` WHERE `ad_id` = '" . $id . "'");
if($res18 && mysql_num_rows($res18) > 0){
while($row18 = mysql_fetch_assoc($res18)){
$picture = $row18['images'];
$pic_id = $row18['id'];
if (file_exists($picture) === true){ ?>
<img src="<?php echo $picture ?>" id="img-<?php echo $picture ?>" class="pictures">
<?php
}
}
}
<script type="text/javascript">
$(document).ready(function(){
// set onclick for all 'a' elements having the 'addition_image_close' class
$('a.addition_images_close').click(function() {
var $pic_id = $(this).prop('data-id');
var $picture = $(this).prop('data-id');
// post to delete.php, sending id=$picture as data and setting success handler
$.post('delete.php', {id: $picture}, function() {
// remove elements from page
$('#img-' + $picture).remove();
$('#a-' + $pic_id).remove();
});
});
});
</script>
and the delete.php has the following:
$id = $_GET['id'];
mysql_query("DELETE FROM `images` WHERE `ad_id` = '".$id."'");
a list.php could be something like this:
<?php
// ...
// render list
if($res18 && mysql_num_rows($res18) > 0) {
while($row18 = mysql_fetch_assoc($res18)) {
if (file_exists($row18['images']) === true){ ?>
<a href="javascript:return(0);"
class="addition_images_close"
data-id=<?php echo $row18['id'] ?>
id="a-<?php echo $row18['id'] ?>"
>X</a>
<img src="<?php echo $row18['id'] ?>"
id="img-<?php echo $row18['id'] ?>"
class="pictures">
}
}
}
?>
<!-- add actions on the links rendered above -->
<script type="text/javascript">
// do this when page is loaded
$(document).ready(function(){
// set onclick for all 'a' elements ahving the 'addition_image_close' class
$('a.addition_image_close').click(function() {
var $id = $(this).prop('data-id');
// post to delete.php, sending id=$id as data and setting success handler
$.post('delete.php', {id: $id}, function() {
// remove elements from page
$('#img-' + $id).remove();
$('#a-' + $id).remove();
});
});
});
with a delete.php receiving an id parameter and performing the delete query

How to get database retrieved value in jquery?

I want to update a likes on database when a user clicks on "like"(same as facebook like). I will load various posts from database. For each posts there is a unique field on database called mid(message Id) and when user clicks "like" below the post i want to increment likes on database for that specific message(it can be through mid). I want to implement this function using jquery because if i pass mid through url it will navigate to that page and get loaded whole page so i need to done it behind the page through AJAX call. Let me show a model how my database retrieval is
$cot = "select * from posts where userid = $usr LIMIT 10";
$ex = mysql_query($cot, $con);
while($cont = mysql_fetch_array($ex))
{
$date = date_create($cont['date']);
$mid = $cont['mid'];
echo "<div id='posts'>";
echo $cont['message'];
echo $photo;
echo "<div class='like'>"; //echo $mid; /* It is to show message id*/
echo "<a href='#'>Like</a></div>"; //When Clicked Like i Want to increment likes on DB
echo "Likes(" . $cont['Likes'] . ")";
echo date_format($date, 'd-m-Y H:i:s');
echo "<hr>";
echo "</div>";
}
i want this to be done over jquery and ajax call. I just need jquery code to call php file increment.php and pass mid(message Id) to that page.
maybe you need something like this:
echo "<a href='javascript:void(0);' class='like' data-mid='".$cont['mid']."'>Like</a></div>"; //When Clicked Like i Want to increment likes on DB
Now this is the script:
<script type="text/javascript">
$(function(){
$(".like").live('click', function(){
$.ajax({
url : 'increment.php',
data : {'mid':$(this).data('mid')},
type : 'POST',
success : function(resp){
if(resp == '1'){
//success message or whatever
}
},
error : function(resp){
alert("some error occured !");
}
});
});
});
</script>
On your increment.php:
<?php
$id = $_POST['mid'];
$sql = "update posts set Likes = Likes+1 where mid = '".$id."'";
//execute the above and return some thing
return 1;
?>
$.post('/increment.php', { mid: whatever });
With your example click handler, it's simple to add this in....
$(document).ready(function() {
$("div.pray").click(function() {
var mid=$(this).val();
alert(mid);
$.post('/increment.php', { mid: mid });
});
});

Ajax/PHP not echoing after first post

I've made a settings page for users and the issue im having is that after you send the form once and say you get an error like "Please fill in all fields" and then you go to submit it again it won't echo out any more errors or success messages but it will update your password.
JS:
<script type="text/javascript">
$(document).ready(function() {
$("#changePassword").click(function(){
var userIdSettings = <?php echo $_SESSION['id']; ?>;
var currPass = $("#currentPass").val();
var newPass = $("#newPass").val();
var newPassRe = $("#newPassRe").val();
$.post("inc/ajax.php", {userIdSettings: userIdSettings, currPass: currPass, newPass: newPass, newPassRe: newPassRe}, function(data){
$(".message").html(data).delay(2000).fadeOut('slow', function(){
});
});
});
});
</script>
PHP:
if ($_POST['userIdSettings']) {
$userIdSettings = $_POST['userIdSettings'];
$currPass = $_POST['currPass'];
$newPass = md5($_POST['newPass']);
$newPassRe = md5($_POST['newPassRe']);
if (!empty($currPass) && !empty($newPass) && !empty($newPassRe)) {
$data = new db();
$data->dbConnect();
$data->dbSelect();
$currPass = md5($currPass);
$checkPass = mysql_query("SELECT * FROM users WHERE id = '$userIdSettings'") or die("Error: ".mysql_error());
$checkPass = mysql_fetch_assoc($checkPass);
if ($currPass == $checkPass['password']) {
if ($newPass == $newPassRe) {
mysql_query("UPDATE users SET password = '$newPassRe' WHERE id = '$userIdSettings'") or die("Error: ".mysql_error());
echo '<div class="messages green large"><span></span>Your password has been updated!</div>';
exit;
} else {
echo '<div class="messages red large"><span></span>Your new passwords dont match!</div>';
exit;
}
} else {
echo '<div class="messages red large"><span></span>Your current password is not correct!</div>';
exit;
}
} else {
echo '<div class="messages red large"><span></span>Please fill in all fields!</div>';
exit;
}
}
$(".message").html(data).show().delay(2000).fadeOut('slow', function(){});
Notice the .show()
You are printing the data to the page, then using the fadeOut method, which at the end result sets display:none. Then you are trying to output more data, but the display is still none, resulting in nothing being displayed on the page, even though the DOM element is being updated. If you add the show() method, this will ensure the CSS value of display is set to block; show the new text for the DOM element; and then fadeOut... slowly... after 2 seconds.

Categories