How to add item/post to favourites - php

I'm trying to create a button which will allow users to favourite certain posts using php and jquery (ajax). I've been trying to use This answer on here to get it all working, but I'm having trouble with getting the post id specific to the post that is meant to be favourited and instead it always gives the post id of the last post to be loaded on the page. Here's my code as it is, but I suspect I've probably just made a mistake in adapting it.
I have 3 tables; Users, Posts and Favourites. In Users I have username password and id, Posts I have id (and content) and in Favourites I have id, userid and postid.
Jquery:
<script>
$(document).ready(function() {
$('.favourite').on('click', null, function() {
var _this = $(this);
var postid = _this.data('$postid');
$.ajax({
type : 'POST',
url : '/add.php',
dataType : 'json',
data : '$postid='+ postid,
complete : function(data) {
if(_this.siblings('.favourite'))
{
_this.html('<img src="add2.png" />');
}
else
{
_this.html('<img src="add1.png />');
}
}
});
});
});
</script>
Main PHP (index.php):
<?php
$getposts = mysql_query("SELECT * FROM Posts ORDER BY id DESC") or die(mysql_query());
while ($row = mysql_fetch_assoc($getposts))
{
$id = $row['id'];
$user = $_SESSION['user'];
$findid = mysql_query("select * from Users where username='$user'");
if ($rows = mysql_fetch_assoc($findid));
{
$userid= $rows['id'];
$postid= $id;
}
echo '<img src="add1.png" />';
}
?>
(There is other code, but it's not related to this section.)
add.php:
<?php
session_start();
require_once('connect.php');
$userid = $_SESSION['$id'];
$postid = $_SESSION['$postid'];
$query_favorite = "SELECT userid, postid FROM Favourites";
$favorite = mysql_query($query_favorite) or die(mysql_error());
$row_favorite = mysql_fetch_assoc($favorite);
$totalRows_favorite = mysql_num_rows($favorite);
if(in_array($_POST['id'], $row_favorite))
{
$Del="DELETE FROM Favourites WHERE userid='$userid' AND postid='$postid'";
$result = mysql_query($Del);
}
else
{
$Add = "INSERT INTO Favourites (userid, postid) VALUES ('$userid', '$postid')";
$result = mysql_query($Add);
}
?>
Thanks in advance for any assistance!

In main.php you are using data-id="' . $postid . '".
Which inserts the postId into the HTML, right?
But in your Javascript you are trying to fetch this data element with
var postid = _this.data('$postid');
data : '$postid='+ postid,
instead of
var post_id = _this.data('id');
data : 'id='+ post_id,
Because your data attribute isn't data-$postid, but data-id.
Same error in add.php:
$userid = $_SESSION['$id'];
$postid = $_SESSION['$postid'];
without single-qoutes:
$userid = $_SESSION[$id];
$postid = $_SESSION[$postid];
Because, when you single-quote the variable, then its the string "$id",
which isn't in $_SESSION.
and you have to fetch $id(postid) from the $_POST data send with your AJAX request. The code missing is: json_decode incoming POST and grab the id, then use it...
Debugging hints:
test that the data is inserted into HTML
add var_dump($_POST); to add.php in order to see the data the AJAX requests posts. The "id" should be part of it.
json_decode() the incoming $_POST to get the ID
and then use it on other variables

Related

How to retrieve multiple data from ajax post function?

I have a select dropdown list and some input fields. My goal is when I select any option from the dropdown list it takes it's value and insert it into the input fields, and that is the ajax post function
<script>
$(document).ready(function(){
$('#productSelect').on('change',function(){
var selectedValue = $('#productSelect').val();
$.post('php/loadProducts.php', {
productId : selectedValue
}, function(data, status) {
$('#id').val(data);
$('#name').val(data);
$('#price').val(data);
});
});
});
</script>
and that is what happens in the "loadProdcut.php" file
<?php
if (isset($_POST['productId'])) {
$productId = $_POST['productId'];
$sql = "SELECT * FROM products WHERE product_id = '$productId';";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$Id = $row['product_id'];
echo $Id;
$Name = $row['product_name'];
echo $Name;
$Price = $row['product_price'];
echo $Price;
}
};
}
?>
Now when I select any option of the dropdown list it inserts all the values (id, name and price) in every single input field, so what I want to achieve is to place every single value into it's input feild.
It's simpler and more reliable to return JSON from an AJAX call to the server if for no other reason than you then return it all in one lump rather than in multiple echo's
Also a prepared statement protects you from bad actors attempting to mess up your database.
I am assuming as you are using a product_id to access a product table there will be only one row returned, so the loop is unnecessary
<?php
if (isset($_POST['productId'])) {
// query with prameter ?
$sql = "SELECT product_id, product_name, product_price
FROM products WHERE product_id = ?";
// prepare it
$stmt = $conn->prepare($sql):
// bind the parameter to its data
$stmt->bind_values('i', $_POST['productId']);
$stmt->execute();
// get resultset from the execution of the query
$result = $stmt->get_result();
$row = $result->fetch_assoc();
//return the row (an array) converted to a JSON String
echo json_encode($row);
}
Now you need to amend the javascript to process the nice object you have just returned.
<script>
$(document).ready(function(){
$('#productSelect').on('change',function(){
var selectedValue = $('#productSelect').val();
$.post('php/loadProducts.php', {productId : selectedValue}, function(data, status) {
$('#id').val(data.product_id);
$('#name').val(data.product_name);
$('#price').val(data.product_price);
});
});
});
</script>

How to only fetch only the new row from MySql automatically?

I am making a messaging service for my users. I used AJAX for sending the message without refreshing the message. I want to fetch the new row from the database automatically (if the current user or the other side user enters any message), without refreshing the older messages.
<div id="readmsg">
#The messages is to be read here....
</div>
<textarea placeholder="Write your message.." id="msg"></textarea>
<input type="submit" value="Send" id="sendmsg">
<?php $user1 = 1; $user2 = 2; ?>
<script type="text/javascript">
$(document).ready(function(){
$("#sendmsg").on("click",function(e){
e.preventDefault();
var usera = <?php echo $user1.";";?>
var userb = <?php echo $user2.";";?>
var msg = $("#msg").val();
$.ajax({
url : "sendmessageprocess.php",
type : "POST",
data : {message:msg, user1:usera, user2:userb},
success : function(data){
document.getElementById("msg").value="";
$("#msg").val("");
}
});
})
});
</script>
As I see in comments the friends only complicated your problem and be far from your main problem
as a chatroom creator in past, I will seriously offer you to use another technologies instead of ajax
But if it's necessary to use ajax, the best way for solving your problem is:
after fetching new messages in your query, put the last row id in a some index in sessions or cookies such as:
$_SESSION['last_msg_id'] = $row['id'];
and in another requests get the messages that their ids is more than your last_msg_id
$query = 'SELECT * FROM `messages` WHERE `id` > "' . $_SESSION['last_msg_id'] . '"';
and, for new clients that haven't your session index get last 10 messages for example and create your session index by the told way. example:
if(isset($_SESSION['last_msg_id'])){
$query = 'SELECT * FROM `messages` WHERE `id` > "' . $_SESSION['last_msg_id'] . '"';
}else{
$query = 'SELECT * FROM `messages` ORDER BY `id` ASC LIMIT 10';
}
// your query process
$rows = {your rows};
foreach($rows as $row){
$_SESSION['last_msg_id'] = $row['id'];
}
// or
$rows = {your rows};
$last_row = end($row);
$_SESSION['last_msg_id'] = $last_row['id']

on append data with ajax call returns only first row from database in jquery and php?

I am working with jquery and php to get data from database onchange particular selection.
My ajax call works fine.but it shows only first row from table.
my ajax call:
$.ajax({
method: "GET",
dataType: 'json',
url:"getdata.php?id="+emp_id,
success:function (response){
$.each(response, function( index, value ) {
$(".bodytable").empty();
$("table.table").append("<tr><td>" + response.emp_name + "</td><td>" + "</td><td><input type='file'></td></tr>");
});
},
});
and below is my query for the same :
if(isset($_GET['id'])){
$explodeVal = $_GET['id'];
$sql = "SELECT * FROM emp_master_new as emn
INNER JOIN emp_info as cti ON emn.id=cti.id
WHERE cti.com_id = '".$explodeVal."' ";
$execute = mysqli_query($con, $sql);
$row=mysqli_fetch_array($execute,MYSQLI_ASSOC);
echo json_encode($row);
}
on success response i only get [object object].
You should get all records from php file by using mysqli_fetch_all as below:
if(isset($_GET['id'])){
$explodeVal = $_GET['id'];
$sql = "SELECT * FROM emp_master_new as emn
INNER JOIN emp_info as cti ON emn.id=cti.id
WHERE cti.com_id = '".$explodeVal."' ";
$execute = mysqli_query($con, $sql);
$row=mysqli_fetch_all($execute,MYSQLI_ASSOC);
echo json_encode($row);
}
Hope it helps you.

unable to delete record with php and ajax

I'm just trying to delete a record by its row id from a table using php and ajax but when I click on the button it neither shows error nor performs the action.
here is my delete.php code:
<?php
session_start();
include 'db.php';
if(isset($_GET['name'])){
$user = $_GET['name'];
$query = mysqli_query($con, "SELECT * FROM login WHERE username='$user'") or die (mysqli_error());
$result = mysqli_num_rows($query);
while($row = mysqli_fetch_array($query)){
$_SESSION['user'] = $row['username'];
}
}
$query = mysqli_query($con, "SELECT * FROM pm WHERE touser = '".$_SESSION['user']."' ORDER BY pmdate DESC" ) or die (mysqli_error());
$result = mysqli_num_rows($query);
while($row = mysqli_fetch_array($query)){
$id = $row['id'];
$delquery = mysqli_query($con, "DELETE * FROM pm WHERE id ='$id'") or die (mysqli_error());
$delresult = mysqli_num_rows($delquery);
}
?>
and here is the ajax and delete code of html
<script>
$("#delete").click(function() {
$.ajax({
type: "POST",
url: "delete.php",
success: function(response){
$("#messages").html(response);
}
});
});
</script>
<div id="messages"></div>
any one have any ideas?
Change you query
-> your "DELETE * FROM pm WHERE id ='$id'"
-> correct "DELETE FROM pm WHERE id ='$id'"
You send POST method true AJAX and in php code you write GET, change it.
you set -> type: "POST" and use a GET method in your link
you then use -> $user = $_GET['name'];
+ did you try to echo GET / POST vars before you query and echo your query ?
+ I guess you send nothing to your page...
+ don't use * in DELETE query
You have few issues in your code.
1. you are not sending any parameters to the delete.php page. Please send the record ID to the delete.php page
2. remove * from DELETE query
3. you are adding PHP variables in HTML anchor tag without using PHP tags. you need to correct the link
4. you need to add event.preventDefault() inside your function

PHP/jQuery AJAX algorithm only working every other time

I am trying to build a page that uses jQuery to call a database every second and return the highest numbered row.
The jQuery code is below (this is in $('document').ready)
var id = 0;
$.post('check.php', 'id=0', function(data){
id = parseInt(data);
$('h1').text(data);
});
var timer = setInterval(function() {
$.post('check.php', 'id=' + id, function(data){
if (data != '')
$('h1').text(data)
else
$('h1').text("NOTHING!");
id = parseInt(data);
});
}, 1000);
And the PHP file, check.php, has the following code (after connecting to the database):
$id = $_POST['id'] - 1;
$query = "SELECT * FROM testtable WHERE 'id' > $id ORDER BY id DESC";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
echo "$row[0]";
When 'id' is the first column.
The highest row number right now is 13. I would expect it to send 13 to the PHP file. $id would then be 12, so it would select all rows with id values higher than 12, returning the row with id value 13. Then it would echo "13", which is sent back to jQuery, which is parsed to an integer, making id equal to 13. Then 13 is sent to the PHP file again a minute later, and the process cycles.
What's actually happening is that it's alternating between displaying "13" and "NOTHING!", and I can't figure out why.
Because select * from tesstable where id > 13 will always be an empty result if 13 is the highest id. What you want is this:
select max(id) as id from testtable
You don't have to send back $id, and if it's got an index on it, this query will return very quickly.
Also, your original query has the column id in quotes, not backticks. You're comparing the string "id" with your variable $id. To top that off, you're susceptible to SQL injection here, so use mysql_escape_string, PDO, or remove the variable reference altogether using the max query provided.
I'll suggest you to do it like this.Try it.And tell if it's working.
var id = 0,count = 0;
$.post('check.php', {id:0}, function(data){
id = +data["rows"]; // Try parse or just a +
$('h1').text(data);
count++;
},"json");
var timer = setInterval(function() {
$.post('check.php', {id:id-count}, function(data){
if (data["rows"] != null || data["rows"] != "")
$('h1').text(data)
else
$('h1').text("NOTHING!");
id = +data["rows"];
count++;
},"json");
}, 1000);
$id = $_POST['id'];
$queryString = ($id == 0) ? "'id' > $id" : "'id' = $id";
$query = "SELECT * FROM testtable WHERE $queryString ORDER BY id DESC";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
echo json_encode(array("rows" => "$row[0]");

Categories