Delete from data base with PHP, Ajax - javascript

Hi I am trying to run a delete script that will delete the record from my database using ajax and php. Used without the ajax javascript file the delete_file.php script works fine and is removed from the database.(So I am asssuming the problem lies in the javascript file somewhere.) Once I add the javascript file only it appears to run and delete_file.php does notk. Basically I pass three id's through to delete_file.php find them all in their respective tables then use those variables to find the right file to delete. Any Help is greatly appreciated. I need a fresh pair of eyes, thanks
What I am Clicking
[![enter image description here][1]][1]
html
<?php echo'<li class="col student_file">
<i class="fa fa-times-circle-o"></i>
<a class="the-file student_'.$student_id.'" id="file_'.$file_id.'" href="/application/student/file_management'.$file_path.'" target="_blank"><i class="fa fa-file-archive-o"></i></i></i>'.$file_name.' <span>'.$file_size.'</span></a>
</li>
delete_file_ajax.js
$(document).ready(function() {
"use strict";
$(".delete-file").click(function() {
var container = $(this).parent();
var id = $('.the-file').attr("id");
var string = 'id='+ id ;
if(confirm("Are you sure you want to delete this?")) {
$.ajax({
type: "POST",
url: "delete_file/delete_file.php",
data: string,
cache: false,
success: function(){
container.slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});
delete_file.php
<?php
session_start();
//Connect to Database
require_once('../../../../db_config.php');
$db_connect = connectDB($mysqli) or die(mysqli_error());
//First lets make sure the user is allowed
require_once('../../../../auth/admin_session.php');
//Create our session on session_id
$session_id = $_SESSION['ADMIN_ID'];
//Get the IDs
$s_id = $_GET['student'];
$a_id = $_GET['agent'];
$f_id = $_GET['file'];
//Lets find the Id of the Agency User
$session_query = mysqli_query($db_connect, "SELECT * FROM agency WHERE agency_id = $a_id");
$session_row = mysqli_fetch_assoc($session_query);
$session_num_rows = mysqli_num_rows($session_query);
$agency_id = $session_row['agency_id'];
//Lets find the Id of the Agency User
$student_session_query = mysqli_query($db_connect, "SELECT * FROM students WHERE student_id = $s_id");
$student_session_row = mysqli_fetch_assoc($student_session_query);
$student_session_num_rows = mysqli_num_rows($student_session_query);
$student_id = $student_session_row['student_id'];
//Lets find the Id of the File we want to delete
$file_session_query = mysqli_query($db_connect, "SELECT * FROM uploaded_files WHERE file_id = $f_id AND agency_id = $a_id AND student_id = $s_id");
$file_session_row = mysqli_fetch_assoc($file_session_query);
$file_session_num_rows = mysqli_num_rows($file_session_query);
$file_id = $file_session_row['file_id'];
if(!mysqli_connect_errno()){
$stmt = $db_connect->prepare("DELETE FROM uploaded_files WHERE file_id = ? AND agency_id = ? AND student_id = ?") or die('We Could not locate the file you wish to delete');
$stmt->bind_param('iii', $file_id, $agency_id, $student_id);
$stmt->execute();
$stmt->close();
}
?>
Solution
html
echo '<form class="delete-student-file" action="delete_file/delete_file.php" method="post">';
echo '<li class="col student_file">';
echo '<input type="hidden" name="student-id" value="'.$student_id.'">';
echo '<input type="hidden" name="agency-id" value="'.$agency_id.'">';
echo '<input type="hidden" name="file-id" value="'.$file_id.'">';
echo'<a class="the-file student_'.$student_id.'" id="file_'.$file_id.'" href="/application/student/file_management'.$file_path.'" target="_blank"><i class="fa fa-file-pdf-o"></i>'.$file_name.' <span>'.$file_size.'</span></a>';
echo '<button class="delete-file" name="submit"><i class="fa fa-times-circle-o"></i></button>';
echo'</li>';
echo'</form>';
delete_file.php
//Get the IDs
$s_id = $_POST['student-id'];
$a_id = $_POST['agency-id'];
$f_id = $_POST['file-id'];
delete_file_ajax.js
$(document).ready(function() {
"use strict";
$(".delete-file").click(function(e) {
e.preventDefault();
var container = $(this).parent();
var formData = $('.delete-student-file').serialize();
if(confirm("Are you sure you want to delete this?")) {
$.ajax({
type: "POST",
url: "delete_file/delete_file.php",
data: formData,
cache: false,
beforeSend: function(){
container.animate({'backgroundColor': '#fb6c6c'}, 300);
},
success: function(){
container.slideUp('slow', function() {$(this).remove();});
}
});
}
});
});

It looks like your problem is sending the ajax call as POST and requesting it as GET. Try this:
$.ajax({
type: "GET",
url: "delete_file/delete_file.php",
data: string,
cache: false,
success: function(){
container.slideUp('slow', function() {$(this).remove();});
}
Personally, I would suggest changing your PHP to accept POST rather than GET, but that is just my opinion.

PHP know inside "" is string not variable,but enclose by '' can print variable
I advice you to use '' in sql query.
$session_query = mysqli_query($db_connect, "SELECT * FROM agency WHERE agency_id = '$a_id'");
OR
$session_query = mysqli_query($db_connect, "SELECT * FROM agency WHERE agency_id = '".$a_id."'");

Related

How, Right Click a <tr>, run php to retrieve data, display result in an alert?

I've read and tried many solutions, none are working. Here is my latest. As you can see all I'm trying to do is display an alert box on screen with the data retrieved from the MySQL using PHP.
My HTML looks like this:
...
<td $brbCols class=\"editCS1\" oncontextmenu=\"getLastLogin('$row[callsign]');return false;\" id=\"callsign:$row[recordID]\" style=\'text-transform:uppercase\'> $row[callsign] </td>
...
Right clicking on the above code runs this,
The getLastLogin javascript looks like this:
function getLastLogin() {
$('tr').on('contextmenu', 'td', function(e) { //Get td under tr and invoke on contextmenu
e.preventDefault(); //Prevent defaults'
var idparm = $(this).attr('id');
var arparm = idparm.split(":");
var id = arparm[1];
id = id.replace(/\s+/g, '');
var call = $(this).html();
call = call.replace(/\s+/g, '');
$.ajax({
type: "GET",
url: "getLastLogIn.php",
data: {call : call, id : id},
success: function(response) {
alert(response);
},
error: function() {
alert('Not OKay');
}
});
});
}
The PHP:
<?php
ini_set('display_errors',1);
error_reporting (E_ALL ^ E_NOTICE);
require_once "creddtls.php";
$call = $_POST['call'];
$id = $_POST['id'];
$sql2 = "SELECT recordID, id, Fname, Lname, grid, creds,
email, latitude, longitude, tactical, callsign, logdate, netID, activity
FROM NetLog
WHERE callsign = '$call'
ORDER BY netID DESC
LIMIT 1,1 " ;
$stmt2 = $db_found->prepare($sql2);
$stmt2->execute();
$result = $stmt2->fetch();
$recordID = $result[0]; $email = $result[6];
$id = $result[1]; $latitude = $result[7];
$Fname = $result[2]; $longitude = $result[8];
$Lname = $result[3]; $creds = $result[5];
$tactical = $result[9]; $grid = $result[4];
$callsign = $result[10]; $netID = $result[12];
$logdate = $result[11]; $activity = $result[13];
$msg = "<b>Last Check-in::</b>
<br>$callsign, $Fname $Lname
<br><b>eMail::</b>$email
<br><b>Was on::</b> $logdate
<br><b>Net ID::</b> $netID, $activity
<br><br>
$recordID
";
echo "$msg";
?>
You are trying to access the data passed via ajax with the wrong superglobal.
You are looking at POST data, but your ajax call is using GET
Change $_POST to $_GET
Wrong or not the code writes to the lli DIV. So I added $("#lli").modal(); to the Javascript to open it in a modal dialog.
All is now well.

Check the input quantity is greater than the available quantity in database

What I want to do is checking whether the text box input quantity is greater than the available quantity in database. Alert should be displayed onclick() of the ADD button.
ADD button
<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); resetform(); checkQty();">ADD</button>
checkQty() function
function checkQty() {
//Grab current forms input field values.
var txtQuantity = document.getElementById("txtQuantity").value;
var listItemName = document.getElementById("listItemName").value;
//Connect to database and verify Quantity Ordered isnt greater than Quantity In Stock.
$.ajax({
type: "POST",
url: "/pms/includes/functions/qty_check.php",
data: 'listItemName=' + listItemName + '&txtQuantity=' + txtQuantity,
}).responseText;
}
qty_check.php
<?php
error_reporting(E_ALL );
ini_set('display_errors', 1);
//Start the Session
if(!isset($_SESSION))
{
session_start();
}
include_once("../../config.php");
require __DIR__."../../dbutil.php";
if(!empty($_POST['txtQuantity'])){$qty = $_POST['txtQuantity'];}
if(!empty($_POST['listItemName'])){$item = $_POST['listItemName'];}
$results = mysqli_query($connection, "SELECT * FROM purchase_items WHERE item_id= ".$_GET['listItemName']"");
$row = mysqli_fetch_assoc($results);
{
$tb_qty=$row["avail_qty"];
}
if($tb_qty < $qty){ ?>
<script type="text/javascript">
alert("Quantity exceeds the stock limit");
</script>
<?php
}
?>
I tried a lot, but I couldn't fix this. Appreciate any help.
You should not print out html directly from an ajax call. You should echo out some json that you can parse on the front end to get the information. using
echo json_encode(['key' => 'value'])
here is your code, with a little modification. I added a dataType to the ajax query and a done function that is called when the ajax request has finished.
function checkQty() {
//Grab current forms input field values.
var txtQuantity = document.getElementById("txtQuantity").value;
var listItemName = document.getElementById("listItemName").value;
//Connect to database and verify Quantity Ordered isnt greater than Quantity In Stock.
$.ajax({
type: "POST",
url: "/pms/includes/functions/qty_check.php",
dataType: 'json',
data: {
listItemName: listItemName,
txtQuantity: txtQuantity
}
}).done(function(response){
alert('check your console!')
console.log('this is the response', response.available);
})
}
qty_check.php
<?php
error_reporting(E_ALL );
ini_set('display_errors', 1);
//Start the Session
if(!isset($_SESSION))
{
session_start();
}
include_once("../../config.php");
require __DIR__."../../dbutil.php";
if(!empty($_POST['txtQuantity'])){$qty = $_POST['txtQuantity'];}
if(!empty($_POST['listItemName'])){$item = $_POST['listItemName'];}
$results = mysqli_query($connection, "SELECT * FROM purchase_items WHERE item_id= ".$_GET['listItemName']"");
$row = mysqli_fetch_assoc($results);
{
$tb_qty=$row["avail_qty"];
}
// echo out some json to send to the front end
echo json_encode(['available' => $tb_qty < $qty]);
?>

Updating div content with jQuery ajax function over PHP

I am trying to update my div content (#update_div) by sending the value of two input fields to a php file (search_value.php) using the .ajax() function from jQuery.
It works, if I just redirect the two values of the input fields using the html form POST method. So the search_value.php should be correct.
My HTML Code:
<form id="my_form">
<input id="food" name="food">
<input id="amount" value="amount in gram" name="amount">
<input type="button" value="Update" id="submit" name="submit" />
</form>
<div id="update_div">
</div>
My Javascript Code:
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php',
type: 'GET',
data: {"food":food,"amount":amount},
success: function(data)
{
$('#update_div').html(data);
}
});
});
My PHP Code:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=calotools', 'root', '');
$food = $GET_['food'];
$amount = $GET_['amount'];
$query="SELECT * FROM nahrungsmittel WHERE name = '$food'";
$user = $pdo->query($query)->fetch();
echo $user['name']."<br />";
echo $user['kcal'] / 100 * $amount;
?>
I do not really get a feedback by clicking the button. Maybe you guys can tell me why?
For GET request, there should not be data part, make it as a query string as below js code:
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php?food='+ food + '&amount='+amount,
type: 'GET',
datatype: "html",
success: function(data)
{
$('#update_div').html(data);
},
failure : function(ex)
{
console.log(ex);
}
});
});
And use $_GET instead of $GET_ in php
Are you running your code after the page has loaded? I've made that mistake several times, and if you're not, I suggest wrapping the whole thing in a $(function(){ /* Everything you have */ });
I prefer using post
in your php script replace $GET_ by $_POST
<?php
$pdo = new PDO('mysql:host=localhost;dbname=calotools', 'root', '');
$food = $_POST['food'];
$amount = $_POST['amount'];
$query="SELECT * FROM nahrungsmittel WHERE name = '$food'";
$user = $pdo->query($query)->fetch();
echo $user['name']."<br />";
echo $user['kcal'] / 100 * $amount;
?>
in your javascript code the result is found in data.responseText
here the new script
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php',
type: 'POST',
data: {"food":food,"amount":amount},
success: function(data)
{
$('#update_div').html(data.responseText);
}
});
});
Tested and your JavaScript code works. The issue may be in the PHP code.
Have you tried correcting the "$_GET" as suggested by others?

How to load AJAX data after new page is loaded

I'm making a website with different products. When a product is clicked, AJAX call gets the product data from the database. After this, I want to go to a new page, where product-data will be displayed. But there is the problem, when the new page is loaded, the data won't be displayed, because the data were loaded at the previous page.
Javascript:
$('#products').on('click', 'li', function(){
document.location.href = "product.html";
var datapk = $(this).attr('data-pk');
console.log(datapk);
$.ajax({
type: 'POST',
url: 'connection.php',
data: {
'function': 'get_product_data',
'datapk': datapk
},
success: function(data) {
var productData = JSON.parse(data);
displayProductData(productData);
}
});
});
PHP:
function get_product_data(){
$datapk = mysql_real_escape_string($_POST['datapk']);
$query = "SELECT * FROM Products WHERE prod_id = '$datapk'";
$result = mysqli_query($GLOBALS['dbc'], $query) or die('Error querying database.');
$json = array();
if (mysqli_num_rows($result)){
while ($row = mysqli_fetch_row($result)){
$json[] = $row;
}
}
echo json_encode($json);
mysqli_close($db_name);
}
Data-pk is the unique ID in database.
As Rory said..
Either it's document.location.href = "product.html"; or $.ajax({ ... })
However, what's the difference between document.location.href = "product.html and <a href='product.html'>, you might ask yourself.

Upvote button on website with JavaScript, Php, AJAX, MySql not working. What am I doing wrong?

I'm trying to create upvote/downvote buttons on a list of articles that I get from a MySql database. The buttons work in the sense that you press on the button and it gets the id of the article. However I can't get the id from article page to the php voting page. When I press the button the database doesn't register the vote. What am I doing wrong?
<script type="text/javascript">
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
alert('you upvoted on '+ dataString);
$(this).fadeIn(200);
$.ajax({
type: "POST",
url: "weblectureupvote.php",
data: dataString,
cache: false,
});
}
else
{
alert('you downvoted on '+ dataString);
$(this).fadeIn(200);
$.ajax({
type: "POST",
url: "weblectureupvote.php",
data: dataString,
cache: false,
});
}
return false;
});
});
</script>
This is the php file:
<?php
$pid = $_POST['id'];
try {
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result=mysql_query("SELECT * FROM database WHERE pid = '$pid' ") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
// temp user array
$lecturelist = array();
$lecturelist["pid"] = $row["pid"];
$lecturelist["upvote"] = $row["upvote"];
$lecturelist["downvote"] = $row["downvote"];
$lecturelist["vote"] = $row["vote"];
}
$upvote= $row["upvote"];
$downvote = $row["downvote"];
$vote = $row["vote"];
$upvote = $upvote + 1;
$query = $db->prepare('UPDATE database SET upvote = :upvote WHERE pid = :pid');
$query->execute(array(
':upvote' => $upvote,
':pid' => $pid
));
$query = $db->prepare('UPDATE database SET vote=:vote WHERE pid = :pid');
$query->execute(array(
':vote' => $vote,
':pid' => $pid
));
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
data: {id: id}
this will get to your php file a "id" variable ( this is the first id ) and with some value ( from the second id )
now
$pid = $_POST['id'];
this should work, as you weren't sending "much" to the server

Categories