How to get database retrieved value in jquery? - php

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 });
});
});

Related

PHP/AJAX - Like button, need some help on the PHP part

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.
};

What is return false in jquery and attr + ajax

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 :)

PHP show message box for update query status

I'm new in PHP, so I'm not sure how to show message box or dialog box containing message to show update query status (the update query is set to work on MYSQL).
--Here is my Code--
session_start();
include_once("../classes/cls_main.php");
$connection = new MainClass();
$connection->createConnection();
$connection->selectDatabase();
$strSQL = "Update tr_routing set Worktatus = 'Sync' ,Sync_Date = Now() WHERE WorkStatus = 'Done' and UserID IN (SELECT UserID FROM ms_user WHERE UserName = '" . $_GET['kode'] . "') ";
$rs = $connection->CRUD_Data($strSQL);
if(mysql_query($strSQL)){
echo "Success update";
}else{
echo "No rows update";
}
$connection->closeConnection();
--End Of Code--
the PHP is trigger by jScript, the jScript is trigger by button on html file.
Thank You in Advance for answering
you may use jquery for this.
var result = $.get( "your_query_file.php", function(data) {
alert( data );
}).fail(function() {
alert( "error" );
});
Put the below code to display the message when rows are updated or if they are not
<?php
if(mysql_query($strSQL))
{
?>
<script>
alert('Rows are updated successfully');
</script>
<?php
}
else
{
?>
<script>
alert('No rows updated');
</script>
<?php
}
?>

jQuery ajax works in Chrome but not Firefox or IE

Fair warning: I am no expert, but I did manage to get this far. My code isn't beautiful and it is rough. It is a fairly complex system so don't be shy to ask questions.
So I have an annoying problem where my code works in chrome but nowhere else. It seems like none of my javascript is working in either Firefox or IE. PLEASE NOTE THAT EVERY TIME YOU SEE PHP INSIDE A DIV IT SIMPLY REPRESENTS THE # OF THE POST INSIDE THE DATABASE.
My code displays posts where each post is paired with a like and dislike button built with spans. There is a checkbox that shows/hides all liked posts and another that does the same for disliked posts when selected. When a user likes or dislikes a post by clicking the button, values are sent to my DB through ajax (to check.php) so they can be recalled on future visits.
Again, it all works fine in Chrome but not in IE and Firefox.
Also, unless I insert the values into my userPosts table in my database manually first, no new posts and values are saved in my DB. For example, if my DB already has values for posts 1-3, all future decisions by the user to like/dislike those posts are sent and saved no problem but if I add a new post (post4) and the user likes or dislikes it, no values get sent... it seems like the INSERT doesn't work in check.php whereas the UPDATE functions just fine.
Here is the jQuery that sits inside the loop, you should find it annotated to your satisfaction:
<script type="text/javascript">
$(document).ready(function() {
// Declare variables
var checked = <?php echo $row['value']; ?>; //get value of Liked or Disliked from database
var postID = <?php echo $row['postID']; ?>; //get post ID from database
var userID = <?php echo $current_user->ID; ?>; //get the wordpress user's ID
var showLikes = $("input[name*='show_likes']"); //represents checkbox for Hide Liked
var showDislikes = $("input[name*='show_dislikes']"); //represents checkbox for Hide Disliked
// Set the remembered Liked and Disliked buttons
if (checked == 1) {
$('#post_<?php echo $row['postID']; ?>').addClass('like');
$('#like_<?php echo $row['postID']; ?>').removeClass('likeimgoff').addClass('likeimgon');
} else if (checked == 0) {
$('#post_<?php echo $row['postID']; ?>').addClass('dislike');
$('#dislike_<?php echo $row['postID']; ?>').removeClass('dislikeimgoff').addClass('dislikeimgon');
}
//When Liked button is clicked do this
$('#like_<?php echo $row['postID']; ?>').click(function() {
// Declare variables
var value = '1';
// Send values to database
$.ajax({
url: 'check.php',
type: 'POST',
data: 'userID=' + userID + '&postID=' + postID + '&value=' + value,
success: function(result) {
$('#Message_<?php echo $row['postID']; ?>').html('').html(result).prependTo('#post_<?php echo $row['postID']; ?>');
}
});
// If post is Disliked, change to Liked
$('#post_<?php echo $row['postID']; ?>').removeClass('dislike').addClass('like');
$('#dislike_<?php echo $row['postID']; ?>').removeClass('dislikeimgon').addClass('dislikeimgoff');
$('#like_<?php echo $row['postID']; ?>').removeClass('likeimgoff').addClass('likeimgon');
// If Hide Liked checkbox is on, toggle the post
if (showLikes.attr('checked')) {
$('#post_<?php echo $row['postID']; ?>').toggle();
}
return false;
});
//When Disliked button is clicked do this
$('#dislike_<?php echo $row['postID']; ?>').click(function() {
// Declare variables
var value = '0';
// Send values to database
$.ajax({
url: 'check.php',
type: 'POST',
data: 'userID=' + userID + '&postID=' + postID + '&value=' + value,
success: function(result) {
$('#Message_<?php echo $row['postID']; ?>').html('').html(result).prependTo('#post_<?php echo $row['postID']; ?>');
}
});
// If post is Liked, change to Disliked
$('#post_<?php echo $row['postID']; ?>').removeClass('like').addClass('dislike');
$('#like_<?php echo $row['postID']; ?>').removeClass('likeimgon').addClass('likeimgoff');
$('#dislike_<?php echo $row['postID']; ?>').removeClass('dislikeimgoff').addClass('dislikeimgon');
// If Hide Disliked checkbox is on, toggle the post
if (showDislikes.attr('checked')) {
$('#post_<?php echo $row['postID']; ?>').toggle();
}
return false;
});
//When Hide Liked checkbox clicked, toggle all Liked posts.
$("input[name*='show_likes']").click(function() {
if ($('#post_<?php echo $row['postID']; ?>').is('.like')) {
$('#post_<?php echo $row['postID']; ?>').toggle();
}
});
//When Hide Disliked checkbox clicked, toggle all Disliked posts.
$("input[name*='show_dislikes']").click(function() {
if ($('#post_<?php echo $row['postID']; ?>').is('.dislike')) {
$('#post_<?php echo $row['postID']; ?>').toggle();
}
});
});
</script>
Here is the code for each post, also sitting in the loop followed by the #Message that appears when the ajax returns the output of check.php and finally closes the loop:
<div id="post_<?php echo $row['postID']; ?>" class="post">
<div id="post_<?php echo $row['postID']; ?>_inside" class="inside">
<div id="like">
<a id="like_<?php echo $row['postID']; ?>" class="likeimgoff" href="#"><span></span></a>
</div>
<div id="dislike">
<a id="dislike_<?php echo $row['postID']; ?>" class="dislikeimgoff" href="#"><span></span></a>
</div>
<b><?php echo $row['Title']; ?></b><br>
<?php echo $row['Description']; ?><br>
</div>
</div>
<div id="Message_<?php echo $row['postID']; ?>" class="reminder"></div>
<?php
}
?>
</div>
Here is check.php:
<?php
mysql_connect("name.database.com", "username", "password") or die(mysql_error());
mysql_select_db("databasename") or die(mysql_error());
if (isset($_POST['userID'])){
$userID = mysql_real_escape_string($_POST['userID']);
}else{
echo "No userID";
}
if (isset($_POST['postID'])){
$postID = mysql_real_escape_string($_POST['postID']);
}else{
echo "No postID";
}
if (isset($_POST['value'])){
$value = mysql_real_escape_string($_POST['value']);
}else{
echo "No value";
}
$query = mysql_query("SELECT * FROM userPosts WHERE userID='$userID' AND postID='$postID';") or die(mysql_error());
if (mysql_num_rows($query) > 0) {
mysql_query("UPDATE userPosts SET value='$value' WHERE userID='$userID' AND postID='$postID';") or die(mysql_error());
} else {
mysql_query("INSERT INTO userPosts (userID, postID, value) VALUES ('$userID', '$postID', '$value') ") or die(mysql_error());
}
echo "UserID: " .$userID. " PostID: " .$postID. " Value: " .$value;
?>
So there you have it. I know it is a lot of code, so please don't shy away and feel free to ask questions!
Sorry, I didn't took the time to read your whole post but usually this type of problems are of a javascript error. If you don't have it, install Firebug on Firefox and see in the firebug console if you have any errors, also look if the ajax call is made and what answer you get.

Table doesn't respond to second jQuery request

My PHP script generates a table with rows which can optionally be edited or deleted. There is also a possibility to create a new Row. The PHP is activated through jQuery Events.
Now all works well, I can edit delete and create an Item. After each action which makes use of the PHP script the HTML table gets updated.
But when I try after an Event to do an action again the HTML Table doesn't get updated though in the background the PHP script makes an entry into the database.
Does someone of you know why my HTML Table doesn't update itself when I trigger a second event?
Here is the Script:
PHP
<?php
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD)
or die ("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME,$dbh)
or die("Could not select printerweb");
$action = $_POST['action'];
$name = $_POST['name'];
$id = $_POST['id'];
if($action == "new")
{
mysql_query("INSERT INTO `place` (`id`, `name`) VALUES (NULL, '$name')");
}
elseif($action == "edit")
{
mysql_query("UPDATE `place` SET `name` = '$name' WHERE `id` = '$id'");
}
elseif($action == "delete")
{
mysql_query("DELETE FROM place WHERE id = '$id'");
}
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=".$row["id"]." class=inputfield_td><input class=inputfield_place type=text value=".$row["name"]." /></td><td class=place_name>".$row["name"]."</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
?>
JS
$(function() {
$.ajax({
url: "place/place_list.php",
cache: false,
success: function (html){
$("#place_container").append(html);
}
});
$(".edit").live("click", function() {
$(this).css("display","none").prevAll(".place_name").css("display","none").prevAll(".inputfield_td").css("display","block").nextAll(".cancel").css("display","block").nextAll(".save").css("display","block").prevAll(".inputfield_td").css("display","block");
});
$(".cancel").live("click", function() {
myvariable5 = $(this).prevAll(".place_name").html();
$(this).css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none").nextAll(".save").css("display","none").siblings().find("input[type=text]").val(myvariable5);
});
$(".save").live("click", function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display","none").prevAll(".cancel").css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none");
$.post("place/place_list.php", {action: "edit", name: ""+myvariable1+"", id: ""+myvariable2+""}, function (html){$("#place_container").replaceWith(html);});
});
$(".delete").live("click", function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
$.post("place/place_list.php", {action: "delete", id: ""+myvariable3+""}, function (html){$("#place_container").replaceWith(html);});
});
$(".new").live("click", function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place/place_list.php", {action: "new", name: ""+myvariable4+""}, function (html){$("#place_container").replaceWith(html);});
});
});
I think I know. You do replaceWith instead of append, so your DIV with ID #place_container disappears after the first operation (you are left with only a table in your page), and of course jQuery does not find it and is unable to refresh it with new content from the second operation.
Just use append or, better yet, html methods.
Shouldnt you replace the complete table ?
$("#place_container").html(html);

Categories