AJAX/Jquery not deleting row from MySQL table - php

I am trying to use AJAX and jQuery to delete a record from a table. The row is being removed from the page view as required, but not from the table.
Im using the following files and related sections:
Query
$result = mysql_query("SELECT id,name FROM myTable");
Query result:
while($row = mysql_fetch_array($result))
{
$id1=$row['id'];
$dataname=$row['name'];
?>
<div class="show">
<span class="name"><?php echo $dataname; ?></span><br><span class="name"><?php echo $id1; ?></span>
<span class="action">Delete</span>
</div>
<?php
}
?>
AJAX Script
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
delete.php
<?php
include('db.php');
if($_POST['id'])
{
$id=mysql_real_escape_string($_POST['id']);
$delete = "DELETE FROM `testdb` WHERE id = '$id1' ";
mysql_query($delete);
}
?>

$id=mysql_real_escape_string($_POST['id']);
$delete = "DELETE FROM `testdb` WHERE id = '$id1' ";
You are using $id1 in the delete statement, it should be $id
$delete = "DELETE FROM `testdb` WHERE id = '$id'";
NOTE : Your code is vulnerable to sql injection, start using
preparedStatement with mysqli_ or PDO
UPDATE: Using PDO to do the delete operation
error_reporting(E_ALL);
ini_set('display_errors', '1');
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', '****', '****');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$id = $_POST['id'] ;
$sql = "DELETE FROM testdb WHERE id = :id ";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

Related

Jquery + Ajax is not working properly, why?

This code will show a counter when there's rows with the status = unread, and it will UPDATE the row to status = read when the user click on the a icon <i class="fas fa-bell"></i>.
The problem is: This is not working propelly, when i click on the <i class="fas fa-bell"></i> it get a delay of 3-9 seconds to update the counter to 0, it update my table instantly, only the counter that get some delay, but sometimes i need to reload the page and click on the icon to update my table, why? What's wrong?
html:
<span class="text-white divCountNT" id="datacount"></span>
script:
<script>
$(document).ready(function(){
$("#datacount").load("select.php");
setInterval(function(){
$("#datacount").load('select.php')
}, 10000);
});
$(document).on('click', '.fa-bell', function (){
$.ajax({
type: "POST",
url: "update.php"
});
});
</script>
select.php:
<?php
require_once 'db.php';
if(!isset($_SESSION))session_start();
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
}
$status = 'unread';
$sql = $conn->prepare("SELECT * FROM noti WHERE status = :status AND user_id = :user_id");
$sql->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();
if($countNT >= 1){
echo $countNT;
}
?>
update.php:
<?php
require_once 'db.php';
if(!isset($_SESSION))session_start();
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
}
$status = 'read';
$sql = $conn->prepare("UPDATE noti SET status = :status WHERE user_id = :user_id");
$sql->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();
echo $countNT;
?>
You dont have a callback function for your ajax call so your table only updates itself with load function. Your ajax call should be something like that :
$.ajax({
type: "POST",
url: "update.php"
}).done(function() {
window.location.reload(true);
});
You can Try with this code It's Working Fine
$.ajax({
type: "POST",
url: "update.php"
success: function(result){
$(body).find("#loadData").html(result);
// $(body).find("#loadData").append(result); //you can also use for append data insted of replace
}
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
check this for use of more methods of AJAX https://www.w3schools.com/jquery/ajax_ajax.asp

variable fails when passing inside a query

I am passing the $place variable to a query in listplace.php using a ajax call. The ajax call works perfectly in php1.php code, but the $place value is not passed over the query. Please help!
listplace.php too works perfectly but when i try to pass $place in where condition it fails.
php1.php code
<select id="name">
<option selected disabled>Please select</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET['place'] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
<?php } ?>
listplace.php
<?php
//connect to the mysql
$db = #mysql_connect('localhost', 'root', 'password') or die("Could not connect database");
#mysql_select_db('test', $db) or die("Could not select database");
$place = $_POST['place'];
$sql = #mysql_query("select product_name from products_list where product_name = '$place'");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r['product_name'];
}
if (count($rows)) {
echo json_encode(['option'=> $rows]);
}else {
echo json_encode(['option'=> false]);
}
?>
An improvement will be to start using prepared statements. This is just an addition to Exprator's answer
This will prevent SQL injection attacks.
$sql_con = new mysqli('localhost', 'root', 'password', 'test');//get connection
$place = $_POST['place'];//posted variable
if($stmt = $sql_con->prepare("select product_name from products_list where product_name =?")) {//prepare returns true or false
$stmt->bind_param("s", $place); //bind the posted variable
$stmt->execute(); //execute query
$stmt->bind_result($product_name);//bind the result from query securely
$rows = array();//create result array
while ($stmt->fetch()) {//start loop
$rows[] = $product_name;//grab everything in array
}
if (count($rows)) {//check for number
echo json_encode(['option'=> $rows]);
} else {
echo json_encode(['option'=> false]);
}
change this line
data: {place: '<?= $_GET['place'] ?>'},
to
data: {place: '<?= $_GET["place"] ?>'},

Interaction between jquery,MySQL and PHP to retrieve the result

I have two file, test.html & test.php. I would like to display the result of an SQL query via jQuery AJAX.
test.php outputs proper JSON, but I'm not able fetch the same on clicking upon the button "Fetch Data". Is it wrong way of using AJAX?
Once fetching the data in test.html, how do I access the contents?
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$ajax({
url:'test.php',
type:'get',
dataType:'json',
success:function(data){
alert(data);
console.log(data['success']);
console.log(data.success);
}
});
});
});
</script>
</head>
<body>
<button>Fetch Data</button>
</body>
</html>
test.php
<?php
$dbuser="root";
$dbname="test";
$dbpass="root";
$dbserver="localhost";
// Make a MySQL Connection
$con = mysql_connect($dbserver, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
// Create a Query
$sql_query = "SELECT ID, UserName, Status FROM user_details1";
// Execute query
$result = mysql_query($sql_query) or die(mysql_error());
$jsonArray = array();
while ($row = mysql_fetch_array($result)){
$jsonArrayItem = array();
$jsonArrayItem["ID"] = $row["ID"];
$jsonArrayItem["UserName"] = $row["UserName"];
$jsonArrayItem["Status"] = $row["Status"];
array_push($jsonArray, $jsonArrayItem);
//echo '<option value='. $row['id'] . '>'. $row['login'] . '</option>';
}
mysql_close($con);
$tableData = array(
"data" => $jsonArray
);
header('Content-Type: application/json');
echo json_encode($tableData,JSON_UNESCAPED_SLASHES);
die();
?>
How do I display/access/print the fetched result contents (AJAX section)?
Make a function like this
var dataToSend = "My Data";
$(button).on("click",function(event){
$.ajax({
method: "POST",
url: "test.php",
data: { pDataToSend: dataToSend }
}).done(function( data ) {
$('.results').empty();
$('.results').append(data);
});
});
And make a div like this
<div class="results></div>
In your PHP file you can read the POST using this code.
$foo = $_POST['pDataToSend'];
Also, your test.php file is all over the place. Use a PDO like this
//connect and setup database example
try {
$db = new PDO("mysql:host=localhost;dbname=second;port=8889","root","root");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
echo 'Could not connect to the database.105';
exit();
}
//select,insert,delete, update from database example
try{
$results = $db->prepare("SELECT * FROM articles WHERE article_id = ? AND user_id = ?");
$results->bindParam(1,$var);
$results->bindParam(2,$var2);
$results->execute();
$hold = $results->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit();
}

Update Text Value in PHP form display using jQuery & MySQL database

I have a table display and I want to enable users to edit the values of the table in a live way using jQuery. The table is simple, it just has 1 column with a list of names. I have it all built out but at the moment the table doesn't update the value. All the code is below, I am still learning everything so it's probably not written very well/correctly! Thanks in advance.
Form Display:
<?php
echo "<div class=\"table-responsive\"><table class=\"table table-striped\">";
echo "<thead><tr><th>Employee Name</th><th></th></tr></thead><tbody>";
require_once 'connectionsettings.php'; // Gets connection settings
$sql = "SELECT id, employees FROM Employees ORDER BY employees ASC";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// what it's saying is that if there's rows do something
while($row = $result->fetch_assoc()) {
// now it's saying get the data and put it in rows
echo "<tr><td data-id='{$row['id']}' contenteditable=\"true\">" . $row["employees"] . "</td><td><span data-id='{$row['id']}' name='remove_{$row['id']}' class='employee glyphicon glyphicon-remove' aria-hidden='true'></span></td></tr>";
}
}else{
echo "No Employees! Let's add some.";
}
$mysqli->close();
echo "</tbody></table></div>";
?>
Jquery Info:
$(function(s){
$("td[contenteditable=true]").blur(function(){
var id = $(this).attr("id") ;
var name = $(this).text() ;
var formURL = "updateemployeename.php";
$.ajax({
url : formURL,
type: "POST",
data : {name: name, id: id},
success:function(data, textStatus, jqXHR)
{
$('#successmessage2').slideDown('fast').delay(1500).slideUp('fast');
$('div#employeedisplay').hide();
$('div#updatedemployeedisplay').load('employeedisplay.php').fadeIn(3000);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
});
s.preventDefault(); //STOP default action
});
SQL Info:
<?php
require_once 'connectionsettings.php'; // Gets connection settings
$name = htmlspecialchars(trim($_POST['name']));
$id = htmlspecialchars(trim($_POST['id']));
$sql = "UPDATE Employees SET employees='$name' WHERE id='$id'";
if($mysqli->query($sql) === TRUE) {
echo "status updated successfully";
}else{
echo "Error updating status" . $mysqli->error;
}
$mysqli->close();
?>

AJAX/JQUERY not updating MySQL row

I am currently trying to update a textarea when a user clicks elsewhere. I'm not well-versed in AJAX and Jquery. However, the script doesn't seem to be updating the row in the DB.
Jquery/Text area:
<textarea id="<?php echo $item_id; ?>_textarea"><?php echo $notes; ?></textarea>
<script type="text/javascript">
$('<?php echo $item_id; ?>_textarea').on('blur',function () {
var notesVal = $(this).val(), id = $(this).data('id');
var itemVal = <?php echo $item_id; ?>;
$.ajax({
type: "POST",
url: "updateNotes.php",
data: {notes:notesVal , id:id, itemId:itemVal},
success: function(msg) {
$('#'+id).html(msg);
}
})
});
</script>
updateNotes.php:
<?php
include('db_connect.php');
include('order_functions.php');
$email = $_SESSION['username'];
$cartId = getcartid($mysqli, $email);
$notes = $_POST['notes'];
$itemID = $_POST['itemId'];
$query = "UPDATE `rel` SET `notes` = '$notes' WHERE `cart_id` = '$cartId' && `id_item` = '$itemID'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if(result) {
return "Notes Updated";
}
?>
You forgot the $ in your last if-statement in your php-code and you should use "echo" (or likewise) instead of "return" as you are not in a function.
<?php
include('db_connect.php');
include('order_functions.php');
$email = $_SESSION['username'];
$cartId = getcartid($mysqli, $email);
$notes = $_POST['notes'];
$itemID = $_POST['itemId'];
$query = "UPDATE `rel` SET `notes` = '$notes' WHERE `cart_id` = '$cartId' && `id_item` = '$itemID'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($result) {
echo "Notes Updated";
}
?>
Your html/javascript-code is a bit wrong. This is how i guess you wanted it to work:
<div id="<?php echo $item_id; ?>_div">
<textarea id="<?php echo $item_id; ?>_textarea" data-id="<?php echo $item_id; ?>"><?php echo htmlentities($notes); ?></textarea>
</div>
$('#<?php echo $item_id; ?>_textarea').on('blur', function () { // don't forget # to select by id
var id = $(this).data('id'); // Get the id-data-attribute
var val = $(this).val();
$.ajax({
type: "POST",
url: "updateNotes.php",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id // Id of the item stored on the data-id
},
success: function (msg) {
$('#' + id + '_div').html(msg); //Changes the textarea to the text sent by the server
}
});
});
Good luck

Categories