Updating Mysql database data using Php and Ajax - php

I'm trying to set up a button which when clicked adds a fixed number to the database value. The database is called var_stat and consists of id and value. The table has one row so far where id = var and value = 35. If clicked, the button should add 5 to the value making it 40.
I'm not sure what to do here, as all answers I found used a completely different approach and strings instead of integers. So far I have done this:
if (isset($_POST['n'])){
$n = $_POST['n'] ;
$stmt = $con->prepare('UPDATE var_stat SET value = value + $n WHERE id = ? ');
$stmt->bind_param('s', $id);
$id = "var";
$stmt->execute();
$stmt->close();
}
<script src="js/jQuery-3.4.1.js"></script>
<script>
function add(n){
$.ajax({
type: "POST",
url: "update.php",
data: {
'n' : n
},
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
<form>
<input type="button" value="+5" class="btn btn-circle btn-grey col-sm-10" onclick="add(5);">
</form>
If I change $n in the update.php to an integer and run the update.php by itself it works, however I can't seem to get this to run through my html page, so I guess there's something wrong with my javascript code?

Bind the n as well, move the id before the binding statement
if (isset($_POST['n'])){
$n = $_POST['n'] ;
$id = "var";
$stmt = $con->prepare('UPDATE var_stat SET value = value + ? WHERE id = ? ');
$stmt->bind_param('is',$n, $id);
$stmt->execute();
$stmt->close();
}

Related

Loop through a list of div using setInterval to refresh data every x seconds

I have this page that consists of a list of user posts / message. When a post is liked, I want it to reflect on all other users, and based on my research setInterval can get the job done by refreshing a specific content for a number of seconds. Currently, I'm having trouble looping through all the user messages and show the updated number of likes. What's happening is that the number displayed is constantly changing and looping through all the values for a single post. Example: If I have 1, 0, and 2 likes respectively on three different posts, the number for the first post changes to 1, 0, and 2 instead of just showing "1". I'm kind of a beginner when it comes to AJAX.
Here's my code:
Jquery / Ajax
function refreshPostLikes() {
setInterval(function() {
$(".posts .id").each(function() { //get id for each post
var postid = $(this).attr("value");
updatePostLikes(postid); //pass the postid variable
});
}, 1000);
}
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {postid: postid}, //send data to php file
success: function(data) {
$(".posts .like").html(data); //output number of likes
}
});
}
PHP Query
<?php
require_once('../connection.php');
$postID = $_POST['postid'];
$likeCountQuery = "select count(*) as total_likes from posts_likes WHERE like_status=1 AND post_id=".$postID; //query number of posts with a like
$likeQueryResult = mysqli_query($conn, $likeCountQuery);
while($likeNumber = mysqli_fetch_assoc($likeQueryResult)) {
$likes = $likeNumber['total_likes'];
if($likes != 0) {
echo $likes;
}
else {
echo '';
}
}
?>
Still not sure this is the best way to go, but the reason your code doesn't work is due to omitting the postid when updating the HTML in the success part of your code.
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {postid: postid}, //send data to php file
success: function(data) {
$(".posts .like").html(data); //output number of likes
}
});
}
with this command $(".posts .like").html(data); //output number of likes
You are updating all the divs which have these classes specified with the same value.
Set postid as id for the div and change the command to
$("#postid").html(data); //output number of likes
is constantly changing and looping through all the values for a single
post
This happens because there is no reference to the post that needs to be updated. What you are doing now is to cycle through all the elements that have the ".posts .id" classes, therefore the update applies to all the posts and not the single one. You should modify your function to make it update only that post (try passing it a unique id in html)
Where N is the id of your post. (For example postid)
Then update the value using this
function updatePostLikes(postid) {
$.ajax({
url: "/main/refresh-post-like.php",
type: "post",
data: {
postid: postid
}, //send data to php file
success: function(data) {
//$(".posts .like").html(data); //output number of likes
$("#post-"+postid).html(data); // in this way we're get the right post
}
});
}
function refreshPostLikes() {
$(".posts .id").each(function() { //get id for each post
var postid = $(this).attr("value");
updatePostLikes(postid); //pass the postid variable
});
setTimeout(refreshPostLikes, 1000); //Check every sec if there are update
}
setTimeout(updateChat, 1000); //Start the check
Prevent SQL Injection
Escape is not enough
<?php
require_once ('../connection.php');
$postID = $_POST['postid']; //Escape this value before use inside the query see linked question
// NEVER TRUST USER INPUT
//$likeCountQuery it could be used for perform a SQL Injection NEVER TRUST USER INPUT
//NEVER !!!
$likeCountQuery = "SELECT COUNT(*) AS total_likes FROM posts_likes WHERE like_status=1 AND post_id=".$postID; //query number of posts with a like
$likeQueryResult = mysqli_query($conn, $likeCountQuery);
while ($likeNumber = mysqli_fetch_assoc($likeQueryResult))
{
$likes = $likeNumber['total_likes'];
if ($likes != 0)
{
echo $likes;
}
else
{
echo '';
}
}
?>

Initialize first ajax data with a preset value then pass it from success response

How can I initialize the lastID in jquery only first time with the value 0 because var lastID = 0; does not work.
I have this ajax script in index.php
<script>
$(document).ready(function () {
var lastID = 0;
function getData() {
$.ajax({
type: 'GET',
url: 'data.php',
data: {lastID: lastID},
dataType: 'json',
success: function (data) {
lastID = data[0].id;
console.log(lastID);
$.each(data, function (i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.id),
$('<td>').text(item.name),
$('<td>').text(item.details)
).appendTo('#output');
});
}
});
}
getData();
setInterval(function () {
getData();
}, 10000); // it will refresh your data every 10 seconds
});
</script>
This is the url: 'data.php' :
$sql = "select * from oders where id > ".$lastID." ORDER BY id DESC";
...
echo json_encode($dataArray);
With this query I get 0 results, and in console (console.log(lastID);) I have no data.
If I change the query like this :
$sql = "select * from oders where id > 0 ORDER BY id DESC";
In console.log(lastID); I get the correct last id. And in html I get the correct data and every 10 seconds it keeps adding same results over and over again.
I can't figure out how to initialize lastID first time as 0 (or the last ID in the database), and on every 10 seconds refresh, take the last ID from the ajax success data.
Where does your $lastID variable come from, how is it defined?
It looks like you are not getting the correct value from the $_GET array.
What you should do to both solve that problem and the sql injection problem you have, is switch to a prepared statement:
$sql = "select * from oders where id > ? ORDER BY id DESC";
And bind $_GET['lastID'] to the placeholder before / during the execution of your query (depending on whether you are using mysqli or PDO).

Clear previous ajax response data before appending new data

I am trying to .append() a selected data from a radio button but it display all the previous respond result.
My HTML :
$sql = "SELECT DISTINCT(name) FROM table1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$i = 1;
while($row = $result->fetch_assoc()) {
echo '<label>'.$row['name'].'</label>';
$sql2 = "SELECT * FROM table1 WHERE list = '".$row['list']."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
echo '<input name="group['.$i.']" class="id" type="radio" data-id="'.$row2['id'].'" />'.$row2['list'];
}
}
$sql2 = NULL;
$i++;
}
}
$sql = NULL;
My ajax to get data and append :
$('.id').on('click', function(){
var id = $(this).data('id');
$.ajax ({
type: 'POST',
url: 'url-here',
data: { id : id },
success : function(data) {
$('#list').append(data);
}
});
});
For PHP side if there is $_POST['id'] then do mysql query to filter from table and return result.
if(isset($_POST['id'])){
$sql = "SELECT * FROM table1 WHERE id = '".$_POST['id']."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<label>'.$row['name'].'</label>';
}
}
}
So what happened in my ajax result box, it keep appending the previous data that been processed by ajax together with the new data.
EDIT : Example append result :
First result of selected radio button : string 1
Second result of selected radio button : string 2
So result should be :
string 1
string 2
Sorry there was a mistake with my explanation. My ajax box result is resulting something like this :
string 1
string 2 (new data from another selected radio)
string 2 (new data is duplicating)
If adding select another radio it will become like this :
string 1
string 2
string 2
string 3 (new data)
string 3 (new data duplicating)
string 3 (new data duplicating)
string 3 (new data duplicating)
My ajax box result :
<div id="list"></div>
Add any class in label and input
echo '<label class="ajax">'....
....
echo '<input class="ajax" ...
....
And Remove in each selection or change in ajax
$('.ajax').remove();
$('#list').append(data);
Or better
$('#list .ajax').remove();
$('#list').append(data);
Update
Or simple add div to your ajax response
$('#list').append("<div class='ajax'>"+data+"</div>");
and then use this code
$('#list .ajax').remove();
$('#list').append(data);
I think you jQuery looks ok. It would be possible for your SQL query to have multiple rows as a result. This could mean that your id value is actually returning two rows. They include the first row and the second row.
You should remove a previously-attached event handler from the elements to avoid multiple click.
$('.id').on('click', function(){
var id = $(this).data('id');
$.ajax ({
type: 'POST',
url: 'url-here',
data: { id : id },
success : function(data) {
$('#list').append(data);
$('.id').off('click'); // remove a previously-attached event handler from the element.
}
});
});

Ajax post request is not functioning

I don't understand why my ajax did not returning any value after post. I am displaying count of registered user in a html table and allowing admin to click each of the count to see list of user name.
My html displaying count of registered user :
$sql2 = "SELECT COUNT(*) AS count FROM reg WHERE reg_id = '".$row['reg_id']."'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
echo '<a class="slot" data-slotid='.$row['reg_id'].' href="">'.$row2['count'].'</a>';
}
}
$sql2 = NULL;
Ajax request :
$('.slot').on('click', function(){
var slotid = $(this).data('slotid');
$.ajax ({
type: 'POST',
url: 'my-domain.com/ajax-request',
data: { slotid : slotid },
success : function(htmlresponse) {
$('#user_list').html(htmlresponse);
console.log(htmlresponse);
}
});
});
My php function from another file to filter database row :
if(isset($_POST['slotid'])){
// Mysql SELECT statement and echo query result
}
If I place a alert(slotid) right after var slotid = $(this).data('slotid'); in the ajax function, it will display the correct value for each of the clicked link. But when I try to echo $_POST['slotid']; at php side, there is not value returned. It seems like the whole page is refreshing.

Value row and empty row added to MySQL table

I'm inputting values into a MySQL database. The values are always being inputted correctly. However, each time a new row enters the table, two rows are being added to the database (one empty row and with a value of either 1 or 2). Any ideas how to stop this empty row being added? Thanks
<div id="post" data-value="1"></div></div>
<div id="post" data-value="2"></div></div>
$('div').click( function(e){
console.log("a")
x= $(e)[0].currentTarget
var data = {"emotion":$(x).context.dataset["value"]}
$.ajax({
type: "POST",
url: "insert.php",
data: data
})
});
insert.php
$number = $_POST["number"];
$sql = "INSERT INTO test(number) VALUES ('$number');";
in your insert.php file check condition
if(isset($_POST["number"]) && $_POST["number"]!='' )
{
$number = $_POST["number"];
$sql = "INSERT INTO test(number) VALUES ('$number');";
}
$('div').click(...
... means you add a click event on any div. Try using
$('div#post').click(...

Categories