I have a problem with my like system an user can give more than 1 like but the system register on the db just one, i think is a problem related to AJAX.
This is the button:
<a class="btn btn-xs btn-white" name="btn" onclick="usercountcomments(<?php echo $value['user_id'].",".$value['personal_closest_id'].",".$value['id']; ?>)"><i class="fa fa-star"></i><span id="countVal1_<?php echo $value['id']; ?>"><?php echo $value['countcomments']; ?></span> Cool </a>
And this one is the jscript AJAX script:
function usercountcomments(user_id,postId,id){
var a = $("#countVal1_"+id).text();
var display = document.getElementById("countVal1_"+id);
var count = a;
var user_comments="cool";
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>social/commentcool/" +user_id+"/"+postId+"/"+user_comments,
data:{ user_comments : user_comments},
success: function(data) {
count++;
display.innerHTML = count;
// alert(a++);
}
});
}
What can I do to prevent the user giving more than one like ?
you can use cookie
<?php
$id =$_GET['id'];
if(isset($_COOKIE['like'.$id])) {
echo "error";
exit;
}else {
$sql = "UPDATE post SET likecount=likecount+1 WHERE id=$id";
$conn->query($sql);
$sql = "SELECT likecount from post where id=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo $row['likecount'];
setcookie('like'.$id,true, time() + (86400 * 30), "/");
}
}
Related
I have this php page with javascript ajax which calls another php file. But every time it calls, it refreshes the page.
I tried these two codes but still it keeps refreshing after calling the `php file:
e.preventDefault();
//and
return false;
But still it keeps redirecting/refreshing to the same page. I don't even have redirecting headers in php file I'm calling.
This is my HTML
<div class="col-md-3 col-sm-6 col-6 ad-image">
<label for="file1">
<img id="blah1" src="http://placehold.it/500" alt="..." class="img-thumbnail">
<input type="button" value="Remove Photo" style="margin-top: 5px;" class="btn btn-danger btn-sm" id="image-remove-btn-1">
<small id="textCount" class="form-text text-center bold">Thumbnail</small>
</label>
</div>
Here's my javascript
$("#image-remove-btn-1").click(function (e) {
e.preventDefault(); //doesn't work still page keeps refreshing
$('#blah1').attr('src', 'http://placehold.it/500');
var userId =<?php echo $userId ?>;
var adId =<?php echo $adId ?>;
deletePhoto('blah1', userId, adId); //this is the function with ajax
$(this).hide();
return false; //doesn't work still page keeps refreshing
});
Here's the deletePhoto() function:
function deletePhoto(imgeName, userid, adId) {
$(document).ready(function () {
$.ajax({
url: 'includes/remove-ad-image-inc.php',
dataType: 'text', // what to expect back from the PHP script, if anything
data: {
userId: userid,
adId: adId,
imgeName: imgeName
},
type: 'post',
success: function (php_script_response) {
alert(php_script_response); // display response from the PHP script, if any
}
});
});
}
This is my php remove-ad-image-inc.php I am calling through above ajax
<?php
include_once './dbConnection.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$userId = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "userId"));
$adId = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "adId"));
$imgeName = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "imgeName"));
if (isset($userId) && isset($adId) && isset($imgeName)) {
$sql = "SELECT * FROM adimage WHERE adimageno=? AND adid=? AND userid=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "error!";
} else {
mysqli_stmt_bind_param($stmt, "sii", $imgeName, $adId, $userId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
$ImageId = $row['adimageid'];
}
$fileName = "../uploads/ad/adImage-" . $ImageId . "-" . $adId . "-" . $userId . "*";
$fileInfo = glob($fileName);
$fileExt = explode(".", $fileInfo[0]);
$fileActualExt = $fileExt[1];
$file = "../uploads/ad/adImage-" . $ImageId . "-" . $adId . "-" . $userId . "." . $fileActualExt;
array_map('unlink', glob($fileName));
$sql = "UPDATE adimage SET adimagestatus=1 WHERE adimageid='$ImageId';";
mysqli_query($conn, $sql);
exit();
}
}
Can someone please help me with a solution?
I have cut this down to be a simple as possible. I create a typeahead variable that works perfectly.
but I need to pass two other variables $php_var1 and $php_var2 that are unrelated to the typeahead. The PHP variables are defined in
start.php. The typeahead script calls search_script.php then calls cart.php. cart.php is were I will need the two PHP variables to
be passed to. Thanks in advance for any help
start.php
<?php
$php_var1 = "my php variable 1";
$php_var2 = "my php variable 2";
?>
<script>
$(document).ready(function() {
var php_var1 = <?php echo $php_var1; ?>;
var php_var2 = <?php echo $php_var2; ?>;
$('#my_input').typeahead({
source: function(query, result) {
$.ajax({
url: "search_script.php",
method: "POST",
data: {
query: query
},
dataType: "json",
success: function(data) {
result($.map(data, function(item) {
return item;
}));
}
})
},
updater: function(item) {
location.href = 'cart.php?shop_name=' + item
return item
}
});
});
</script>
<form action="cart.php" action="post">
<input type="text" id="my_input" placeholder="Typeahead Search" />
</form>
search_script.php
<?php
$php_var1 = isset($_REQUEST['php_var1']) ? $_REQUEST['php_var1'] : "empty";
$php_var2 = isset($_REQUEST['php_var2']) ? $_REQUEST['php_var2'] : "empty";
$connect = mysqli_connect($servername, $username, $password, $dbname);
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = " SELECT * FROM all_shops WHERE p_shop_name LIKE '%".$request."%'";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row["p_shop_name"];
}
echo json_encode($data);
}
?>
cart.php
$php_var1 = isset($_REQUEST['php_var1']) ? $_REQUEST['php_var1'] : "empty";
$php_var2 = isset($_REQUEST['php_var2']) ? $_REQUEST['php_var2'] : "empty";
echo $php_var1;
echo $php_var2;
?>
You need quotes around the php output in order to generate javascript strings
var php_var1 = "<?php echo $php_var1; ?>";
var php_var2 = "<?php echo $php_var2; ?>";
Stackoverflow is an excellent resource, but sometimes you don't get the answer, so you need to persevere and keep trying. I worked on this all day yesterday and just couldn't figure it out. Woke up this AM and it came to me. The answer is as follows. In the typeahead script change the following line
location.href = 'cart.php?shop_name=' + item
to
location.href = 'cart.php?shop_name=' + item + '&php_var1=<?php echo $php_var1 ?>' + '&php_var2=<?php echo $php_var2 ?>'
JS
<script>
function myAjax() {
$.ajax({
type: "POST",
url: 'ajax.php',
data:{action:'call_this'}
});
</script>
HTML
<a href="'. $row['link'] .'"target="_blank" onclick="myAjax()">
PHP
<?php
require ("static/php/inc/betaconfig.inc.php");
if($_POST['action'] == 'call_this') {
$conn->query("UPDATE users SET clicks = (clicks + 1) WHERE id = 13");
}
?>
Normally it should be $uid instead of 13 but I don't know how to do that too...
First of all, why this doesnt work ? 2nd $uid is $id = $_REQUEST['id']; and then
$sql = "SELECT * FROM `link` WHERE id = '$id'";
$result4 = $conn->query($sql);
while($row = $result4->fetch_assoc()) {
$uid = $row['userid'];
}
so the best thing that instead of 13 I could use $uid
i'm trying to make a notification tab work but do not seem to get it right. The dropdown is working fine but the ajax call to newfriends.php is not working right, when viewed with firebug there are no results to be seen in the dropdown.Quite confusing.
(note the dropdown menu is located in header and can only be displayed if the session is initialised)
here is the ajax used in jquery:
function load_notifications(view=''){
$.ajax({
url: "notification/new_friends.php",
method: "POST",
data:{view:"view"},
dataType:"json",
success: function(data){
$(".dropdown-menu").html(data.notification);
if(data.unseen_notification>0){
$(".badge1").html(data.unseen_notification);
}
}
});
//$(".dynamic-notification").load("notification/pm_n.php");
// $(".dynamic-notification-f").load("notification/new_friends.php");
};
load_notifications();
$(document).on("click",".count_friend", function(){
load_notifications('yes');
});
//loads every 2 seconds for chat
setInterval(function(){load_notifications();},2000);
here is the new_friends.php content:
<?php
include '../includes/dbconfig.inc.php';
if (isset($_POST['view'])) {
if($_POST['view'] !=''){
$update="update friends set count='1' where friend_one=:session and count='0'";
$stmt=$conn->prepare($update);
$stmt->bindValue(":session", $_SESSION['uname']);
$stmt->execute();
}
$sql123="select id from friends where friend_two=:sess_uname and count='0'";
$stmt123=$conn->prepare($sql123);
$stmt123->bindValue(":sess_uname", $_SESSION['uname']);
$stmt123->execute();
$request_count=$stmt123->fetchColumn();
//$count_friend=$stmt123->rowCount();
/*$sql_f_count="select *from user where user_id=:session_id and activated='1' limit 1";
$stmt_f_count=$conn->prepare($sql_f_count);
$stmt_f_count->bindValue(":session_id", $_SESSION['id']);
$stmt_f_count->execute();
$user_details=$stmt_f_count->fetchAll();
$friend_badge=$user_details[0]['friend_count_badge'];*/
require "notification/friend_request_notification.php";
// $new_friends="<span class='dropdown'><a href='#' data-placement='bottom' class='btn dropdown-toggle' data-toggle='dropdown' title='Friend Requests' data-html='true'><span class='count_friend' style=' height:33px; width:30px;'><span class='badge1 label label-pill'>".$count."</span><img src='img/logo/group-button-white.png' style='height:25px; width:27px;' alt='new_friends_alert'></span></a><ul class='dropdown-menu'></ul></span>";
//if($request_count[0]>0){
//$new_friends="<a href='#' data-placement='bottom' class='btn' data-trigger='focus' title='Friend Requests' data-toggle='popover' data-html='true' data-content='".$friend_requests."'><span class='count_friend' style=' height:33px; width:30px;'><img src='img/logo/group-button-white.png' style='height:25px; width:27px;' alt='new_friends_alert'></span><span class='badge'>".$friend_badge."</span></a>";
/*}else{
$new_friends="<a href='all_notifications.php'><img src='img/logo/group-button-black.png' style='height:25px; width:27px;' alt='new_friends_alert'></a>";
}*/
//echo $new_friends;
//}
$data=array(
'notification'=>$friend_requests,
'unseen_notification' =>$request_count[0][0]
);
}
echo json_encode($data);
and the code for friend requests output:
<?php
//error_reporting(0);
require_once 'includes/dbconfig.inc.php';
$sql = "select * from friends where friend_two=:session and accepted='0' order by friends_date_made asc";
$stmt = $conn->prepare($sql);
$stmt->bindparam(":session", $_SESSION['uname']);
$stmt->execute();
$numrows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$friend_requests="";
if ($numrows < 1) {
$friend_requests = "You do not have any friend requests";
echo "$friend_requests";
exit();
} else {
foreach ($numrows as $i=>$row1 ) {
$reqid = $row1['friend_id'];
$user1 = $row1['friend_one'];
$datemade = $row1['friends_date_made'];
$datemade1 = strftime("%B %d, %y", strtotime($datemade));
$sql = "SELECT * FROM user WHERE uname=:user1 LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindparam(":user1", $user1);
$stmt->execute();
$thumbrow = $stmt->fetchAll(PDO::FETCH_ASSOC);
$user1avatar = $thumbrow[$i]['avatar'];
$user1id=$thumbrow[$i]['user_id'];
if ($user1avatar =="") {
$user1pic = '<img src="img/avatardefault.png" height="50" style="float:left;" width="50" alt="'.$user1.'" class="user_pic">';
} else {
$user1pic = '<img src="../user/user/'.$user1id.'/'.$user1avatar.'" height="50" style="float:left;" width="50" alt="'.$user1.'" class="user_pic">';
}
$friend_requests .= '<li><div id="'.$reqid.'" float="right" class="friendrequests">
'. $user1pic .'
<div class="user_info '.$reqid.'" id="'.$reqid.'"><small>' . $datemade1 . '</small>
'.$user1.' is requesting your friendship<br /><br />
<button id="'.$reqid.'" name="'.$_SESSION['uname'].'" sess="'.$_SESSION['id'].'" class="accept_btn btn btn-warning">Accept</button><span class="show-spinner"></span> or
<button id="'.$reqid.'" name="'.$_SESSION['uname'].'" sess="'.$_SESSION['id'].'" class="reject_btn btn btn-warning">Reject</button>
</div>
</div><hr></li>';
}
}
You currently have data:{view:"view"}.
Which means that you are passing string 'view' in the body of your request.
Change it to something like:
function load_notifications(thisview=''){
var theData = {
view: thisview
}
$.ajax({
url: "notification/new_friends.php",
method: "POST",
data: theData,
dataType:"json",
success: function(data){
I want to insert a "remove" button in each of these divs, so that the database's row and the div can be deleted using the remove button.
Number of divs vary according to the number of rows in the database.
It should appear as follows,
Showing data works just fine. But, delete (remove button) doesn't work.
PHP
function deleteUser($connection, $userID){ // this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
header("Location: main.php");
} else {
echo "Error! ";
}
}
function currentUsers($connection){
$sql1 = "SELECT * FROM users_table ";
$result1 = mysqli_query($connection, $sql1);
if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['user_id'];
$name = $row['name'];
$country = $row['country'];
echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
</div>';
if (isset($_GET['removeButton'])) {
deleteUser($connection, $userID);
}
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
currentUsers($connection);
?>
As the discussion from the comment, The following codes given.
Updated HTML:
<input type="button" name="removeButton" value="Remove" class="removeBtn">
Javascript:
var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
$.post("page.php", { userID : userID}, function(result){
if(result == "Success") window.location.href = "main.php";
else alert(result);
});
});
page.php
//need the database connection
$userID = $_POST['userID'];
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
echo 'Success';
} else {
echo "Error! ";
}
If you want to remove the total div as well with the database field then use:
Javascript:
var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
var __this = $(this);
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});
If you want to pass your $userID in each input then use:
<input data-userid = <?php echo $userID;?> type="button" name="removeButton" value="Remove" class="removeBtn">
Javascript
$(".removeBtn").on("click", function(){
var __this = $(this);
var userID = __this.attr("data-userid");
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});
This is just an answer of your question, but you have to use this as you want. This may help you, try and let me know what happens.
The remove button doesnt work because you never get into deleteUser() method.
You cant just write
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
as it was inside a form. For it to trigger, write it like this:
<form method="GET">
<input type = "submit" name = "removeButton" value = "<?php echo $userID;?>">
</form>
Then, when calling
deleteUser($connection, $_GET['removeButton']);
Hope this helps.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function deleteUser($connection, $userID){ // this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
header("Location: main.php");
} else {
echo "Error! ";
}
}
function currentUsers($connection){
$sql1 = "SELECT * FROM maps ";
$result1 = mysqli_query($connection, $sql1);
if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['id'];
$name = $row['name'];
$country = $row['country'];
echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
</div>';
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
if (isset($_GET['removeButton']))
{
deleteUser($connection, $_GET['removeButton']);
}
currentUsers($connection);
?>