I'm trying to create this like button which goes +1 after clicking on it. You can only click the like once (like is bonded to the account with what u logged in, so a user can not 15x like the same post.)
In my HTML I have this button
<a class="like" id="<?php echo $rows['id']; ?>" href="index.php?id=.$rows['ID']">like</a>
As my AJAX/JQuery I have these
$('a.like').on('click',function () {
var id = $(this).attr('id');
$.ajax({
url:"ajax/post_like.php",
method: "POST",
data: ({ id: id }), // first id is the name, second is the actual id variable we just created
beforeSend: function(data) {
// you can do stuff in here before you send the data, display spinner gif etc
alert('sending the like');
},
success: function(data) {
// same here but when the ajax request is successful
// the data variable is coming from the echo of your PHP script
alert(data);
},
complete: function(data) {
// yet again but on completion
alert('completed the like');
}
});
// stops the browser following the link (href) in the a tag
return false;
});
Now here is the part where I am struggling, mainly the PHP handling. We have created a load more button which loads more posts which works well. The code is as follows. How can I know work out the like part in the same way as the load more button?
<?php
include_once("../classes/db.class.php");
session_start();
$userid = $_SESSION['userid'];
$output = "";
$limit = $_POST['limit'];
if(isset($limit)){
if($limit != ""){
$conn = db::getInstance();
$query ="SELECT posts.id, posts.post_title, posts.picture ,posts.description, posts.location, posts.post_date
FROM posts
INNER JOIN friends
ON posts.user_id = friends.user1_id OR posts.user_id = friends.user2_id
WHERE friends.user1_id='$userid' OR friends.user2_id='$userid'
ORDER BY posts.post_date DESC
LIMIT $limit";
$result = $conn->prepare($query);
$result->execute();
while($row = $result->fetch()) {
$output.=' <div class="post">';
$output .='<div class="post_desc"><p>'. $row['post_title'].'</p></div>';
$output .='<div class="post__picture"><img src="'. $row['picture'].'" alt=""></div>';
$output .='<div class="post_desc"><p>'. $row['description'].'</p></div>';
$output .=' <div class="post_date">'. $row['post_date'].'</div>';
$output .='</div>';
};
echo $output;
}
}
else{
}
?>
Our database is as follows.
Assuming you can set the id column freely, and the userid and postid sections are alphanumerical, you can require the id column to be unique. The following will then always work:
include_once("../classes/db.class.php");
$conn = db::getInstance();
$userid = $_SESSION['userid'];
$postid = $_POST['id'];
$id = "$userid/$postid";
$query = "INSERT INTO likes (id, user_id, post_id) VALUES ('$id', '$userid', '$postid')";
if ($conn->query($sql) === TRUE) {
echo json_encode({postid: postid});
} else {
// There was a small problem processing the like
// You might want to add a check in your success function just to be sure
header('HTTP/1.1 500 Internal Server Error');
}
However, be sure to add a few tests to prevent SQL injections (e.g. by ensuring $postid consists only of integers). If no such guarantee can be made, you should check out this thread.
Otherwise (e.g. if id is generated using AUTO_INCREMENT), you'd have to add a test which tries to retrieve ($userid, $postid) to check if it doesn't exist already:
if (conn->query("SELECT 1 FROM likes WHERE userid=$userid AND postid=$postid")->num_rows == 0) {
// Place the code starting from `$id = ` in here.
};
Related
I am working on a web application where it allows you to post a simple comment to the database on a form submit, what I want to do is generate a new list of all comments written and use AJAX to replace a div where comments are to be stored, this to show the newest written comment after submitting it.
$(document).ready(function() {
$('#postCommentForm').submit(function (e)
{
e.preventDefault();
console.log("JS Submitted");
function addCommentAJAX_call(commentTitleBox,commentBox,source_name,place_id,city_id)
{
$.ajax(
{
url : "funcsAJAX.php",
type : "post",
dataType : "json",
data : {
'commentTitleBox' : commentTitleBox,
'commentBox' : commentBox ,
'source_name' : source_name ,
'place_id' : place_id ,
'city_id' : city_id
},
success : function(response)
{
console.log(response);
$('#g').html(response);
},
});
}
var commentTitleBox = $('#commentTitleBox').val();
var commentBox = $('#commentBox').val();
var source_name = $('#source_name').val();
var place_id = $('#place_id').val();
var city_id = $('#city_id').val();
addCommentAJAX_call(commentTitleBox,commentBox,source_name,place_id,city_id);
});
});
This is the jQuery code I use to pull data from the form and post it to the webserver, note that the success part is unfinished as it never fired for me, #g is the div which contents I want to replace.
Next is the handler for the AJAX call
extract($_POST);
#addCommentAJAX_call handler
$user = 'user';
$pass = 'pass';
try
{
$db = new PDO('mysql:host=localhost;dbname=twincities;charset=utf8',$user,$pass);
}
catch(PDOException $e)
{
die("<h3>connection to be failed, not surprising really heres why ".$e->getMessage());
}
addComment($db,$city_id,$place_id,$commentTitleBox,$commentBox,$source_name);
$allComments = showCommentsForAJAX($db,$city_id,$place_id);
$db->connection = null;
echo json_encode($allComments);
This will create PDO object and then addComment() will add the comment to the database, it works fine with no issues.
showCommentsForAJAX() is the function I want to use that returns the comments from the database
function showCommentsForAJAX($db,$cityID,$placeID)
{
try
{
if($cityID && $placeID)
{
$query = "select * from comment where place_place_id = :place_place_id and city_city_woeid = :city_city_woeid";
$queryVars = ['place_place_id' => $placeID,'city_city_woeid' => $cityID];
}
else if($cityID)
{
$query = "select * from comment where city_city_woeid = :city_city_woeid";
$queryVars = ['city_city_woeid' => $cityID];
}
$query = $query." ORDER BY `timestamp` desc";
$stmt = $db->prepare($query);
$stmt->execute($queryVars);
$returnHTML = "";
$returnHTML = $returnHTML . '<div id=comments>';
while($comment = $stmt->fetch())
{
$returnHTML = $returnHTML . '<div id=commentIDis'.$comment['comment_id'].'>
<h3>'.$comment['title'].'</h3>
<br>
<p>'.$comment['content'].'</p>
<br>
<p>-'.$comment['source_name'].'</p>
<br>
';
$returnHTML = $returnHTML . '</div>';
}
$returnHTML = $returnHTML . '</div>';
return $returnHTML;
}
catch(PDOException $e)
{
die("<h3> ROLLBACK something broke, not surprising really heres why ".$e->getMessage());
}
}
I want to based off the entries in the database, to build the comments' HTML and return that to AJAX, I am not sure how to encode the result for AJAX to understand it, and I believe that the logic for $returnHTML is incorrect and there is a better method of doing what I want but I am not sure how to achieve that, I have done a similar thing using Flask before where I used jinja templating to generate the HTML and successfully replace the contents of a div, but due to this university project I need to use PHP.
Suggestions to code layout are also very appreciated
I want my header to be consequently refreshed with fresh values from my database.
To achieve it i have created an AJAX post method:
AJAX (edited):
$(document).ready( function () {
function update() {
$.ajax({
type: "POST",
url: "indextopgame.php",
data: { id: "<?=$_SESSION['user']['id']?>"},
success: function(data) {
$(".full-wrapper").html(data);
}
});
}
setInterval( update, 5000 );
});
It should pass $_SESSION['user']['id'] to indextopgame.php every 10 seconds.
indextopgame.php looks like that:
PHP PART (edited):
<?php
session_start();
$con = new mysqli("localhost","d0man94_eworld","own3d123","d0man94_eworld");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$id = trim(sql_safe($_POST['id']));
$data = "SELECT username, email, user_role, fbid, googleid, fname, lname, avatar, energy, energymax, health, healthmax, fame, edollar, etoken, companies, workid, city, function FROM members WHERE id = $id";
$result = mysqli_query($con, $data);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$_SESSION['user']['user_role'] = $row["id"];
$_SESSION['user']['fbid'] = $row['fbid'];
$_SESSION['user']['googleid'] = $row['googleid'];
$_SESSION['user']['created'] = $row['created'];
$_SESSION['user']['lastlogin'] = $row['lastlogin'];
$_SESSION['user']['username'] = $row['username'];
$_SESSION['user']['fname'] = $row['fname'];
$_SESSION['user']['lname'] = $row['lname'];
$_SESSION['user']['email'] = $row['email'];
$_SESSION['user']['avatar'] = $row['avatar'];
$_SESSION['user']['energy'] = $row['energy'];
$_SESSION['user']['energymax'] = $row['energymax'];
$_SESSION['user']['health'] = $row['health'];
$_SESSION['user']['healthmax'] = $row['healthmax'];
$_SESSION['user']['fame'] = $row['fame'];
$_SESSION['user']['edollar'] = $row['edollar'];
$_SESSION['user']['etoken'] = $row['etoken'];
$_SESSION['user']['companies'] = $row['companies'];
$_SESSION['user']['workid'] = $row['workid'];
$_SESSION['user']['city'] = $row['city'];
$_SESSION['user']['function'] = $row['function'];
}
echo $_SESSION['user']['energy'];
}
}
?>
Still this wouldn't update the header with values i want, instead it just makes the header disappear. What's wrong with this code? Maybe there are other, more effective methods to refresh values from MySQL?
EDIT:
I've edited the AJAX / PHP code samples - it's working like that! But how may I echo all those variables? Echoing one after another seems to cause error again, since values will disappear from my header.
EDIT2:
Solved, I made a silly mistake with syntax... Thanks everyone for contributing!
You are not using the data that is sent back from the server in your ajax call:
success: function() {
$(".full-wrapper").html(data);
}
});
Should be:
success: function(data) {
^^^^ the returned data
$(".full-wrapper").html(data);
}
});
You should also check that your php script actually echoes out something useful.
data options is missing in success method
success: function(data) {
$(".full-wrapper").html(data);
}
Also you should have to echo that content in php file which you want to show in header.
First let me show you the code
This is the script
var user_id = $(this).attr("id");
var datastring = 'user_two='+ user_id;
$(".follow").click(function(){
$.ajax({
type: "POST",
url: "include.php",
data: datastring,
success: function(html){}
});
$("#follow"+user_id).hide();
$("#unfollow"+user_id).show();
return false;
});
Here is php
<?php
$query = $handler->query("SELECT * FROM users");
while ($row = $query->fetch()) {
$user_two = $row['id'];
$user_one = 1;
?>
<p><?php echo $row['username'];?></p>
<?php
$follow_check = $handler->query("SELECT * FROM follow WHERE user_one='$user_one' AND user_two='$user_two'");
if ($follow_check->rowCount() == 0) {?>
<div id="follow<?php echo $user_one;?>">
Follow
</div>
<div id="unfollow<?php echo $user_one;?>" style='display:none'>
Following
</div>
<?php }else{?>
<div id="follow<?php echo $user_one;?>" style='display:none'>
Follow
</div>
<div id="unfollow<?php echo $user_one;?>" >
Following
</div>
<?php } ?>
<?php } ?>
Here is the php for Insert query
<?php
include('db.php');
$user_two = $_POST['user_two'];
$query = $handler->query("INSERT INTO follow (user_one,user_two) VALUES ('1','$user_two')");
?>
there two things i need to insert which is user_one = Session=0 or the current logged in user but i just made it static for the mean time and the user_two which is the users id or the one you will click to follow that person. But idk how to do it in ajax, like in php you can get the value of the link like <a href="?id="> and then to get the value, $_GET['id'] but idk how to store that value to script
I just need an explanation on user_id = $(this).attr("id");
and the return false inside the $(".follow").click and when I make it to false i need to refresh the page just to see the changes of links to follow and following why is it like that?
By the way, When i click the follow link it will successfuly insert to the database but the user_two's value is always 0 because I dont know how to store link id to the script.
Not 100% sure if i understood but let me try:
First: id="<?php echo $user_id; ?>" it's ok.
You can get it with var user_id = $(this).attr("id");
Maybe you should move this line inside the $(".follow")... block
$(".follow").click(function() {
var user_id = $(this).attr("id"); //"this" will refer the element with the "follow" class. Then user_id will be the value of the id for the clicked element.
$.ajax({
type: "POST",
url: "include.php",
data: {user_two: user_id}
}).done(function(data) {
data = JSON.parse(data);
if(data.msg) {
//everything is ok
$("#follow"+user_id).hide();
$("#unfollow"+user_id).show();
} else {
//handle the error
}
)}
});
PHP part:
<?php
include('db.php');
$user_two = $_POST['user_two'];
$query = $handler->query("INSERT INTO follow (user_one,user_two) VALUES ('1','$user_two')");
if($query) { //check if query ran successfully
echo json_encode(array("msg" => 1)); 1 for success
} else {
echo json_encode(array("msg" => 2)); 2 for error
}
?>
As for the "what is return false in ajax":
.follow -> targets an tag. Clicking on an a tag makes your browser navigate to the url specified in href="". return false disables this behaviour as you don't need the page to refresh or go to another page :)
I'm trying to build a profile view counter with PHP and jquery ajax. I want the page count to be fetched, and incremented and input into the database when the page is loaded.
Here is my jquery:
var views = "<?php echo $views;?>";
$(document).ready(function(){
view = parseInt(views) + 1;
$.ajax({
url: "user.php",
type: "POST",
data: {
'views' : view //array of objects
},
success:function(data, response){
console.log(data);
alert(view);
}
});
and the php that picks up the ajax:
if(isset($_GET["id"]) && isset($_GET['activ'])){
$activ = preg_replace('#[^0-2]#i', '', $_GET['activ']);
$id = preg_replace('#[^a-z0-9]#i', '', $_GET['id']);
} else {
header("location: http://www.unlimitedtutors.com");
exit();
}
if (isset($_POST['views'])){
$views = mysql_real_escape_string($_POST['views']);
$views = intval($views);
$sql1 = "UPDATE users SET views='$views' WHERE id='$id' LIMIT 1";
$query1 = mysqli_query($db_conx, $sql1);
echo $id;
}
the problem is that the $id variable doesnt seem to be showing up although I know it's been declared. This obviously means that the sql is not working correctly. Does anyone have any suggestions?
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 });
});
});