jQuery ajax delete script not actually deleting - php

I have a little personal webapp that I'm working on. I have a link that, when clicked, is supposed to make an ajax call to a php that is supposed to delete that info from a database. For some unknown reason, it won't actually delete the row from the database. I've tried everything I know, but still nothing. I'm sure it's something incredibly easy... Here are the scripts involved.
Database output:
$sql = "SELECT * FROM bookmark_app";
foreach ($dbh->query($sql) as $row)
{
echo '<div class="box" id="',$row['id'],'"><img src="images/avatar.jpg" width="75" height="75" border="0" class="avatar"/>
<div class="text">',$row['title'],'<br/>
</div>
/*** Click to delete ***/
x</div>
<div class="clear"></div>';
}
$dbh = null;
Ajax script:
$(document).ready(function() {
$("a.delete").click(function(){
var element = $(this);
var noteid = element.attr("id");
var info = 'id=' + noteid;
$.ajax({
type: "GET",
url: "includes/delete.php",
data: info,
success: function(){
element.parent().eq(0).fadeOut("slow");
}
});
return false;
});
});
Delete code:
include('connect.php');
//delete.php?id=IdOfPost
if($_GET['id']){
$id = $_GET['id'];
//Delete the record of the post
$delete = mysql_query("DELETE FROM `db` WHERE `id` = '$id'");
//Redirect the user
header("Location:xxxx.php");
}

Ah just spotted your error, in the href you're generating you're not setting the id attribute. It should be something like:
x
Of course that's just an immediate example, you must escape these kinds of things but this should let you access the item in jQuery.

You may want to modify your delete script to not just redirect after the DB query. Since it's being called via AJAX, have it at least return a success/error code to the javascript:
// can't return $delete unconditionally, since *_query() returns an object
if ($delete) {
return(json_encode(array('code' => 1, 'msg' => 'Delete succeeded')));
} else {
return(json_encode(array('code' => 0, 'msg' => 'Delete failed: ' . mysql_error()));
}
It's bad practice to assume a database call succeeded.

Related

Delete data from table with AJAX and PHP

Can you explain me where is the problem? Because I lost all my hope for this...
Insert and load work but delete not... When I remove if statement from delete, it says id is undefined index. But why it should be undefined when I define it in var id = $(this).data("id3"); I think the problem will be somewhere in select.php with a button.
I have lack of experience with AJAX so I ask you for help with this problem.
Thank you for response. (sorry for the language)
Index.php
$('.btn_delete').on('click', function()
{
var id = $(this).data("id3");
if (confirm('Naozaj zmazat ?')) {
$.ajax({
url: 'delete.php',
type: 'POST',
data: {delete: 1, id: id},
success: function(data)
{
alert(data);
fetch_data();
}
});
}
});
delete.php
if (isset($_POST['delete'])) {
include("db.php");
$id = mysqli_real_escape_string($conn, $_POST['id']);
$sql = "DELETE FROM suciastka WHERE id_suciastka = '".$id."'";
if (mysqli_query($conn, $sql)) {
echo "Deleted";
}
}
And here is my select.php
include("db.php");
$output = "";
$sql = "SELECT * FROM suciastka";
$result = mysqli_query($conn, $sql);
$output .= "
<div class='table-responsive'>
<table class='table table-bordered'>
<tr>
<th>ID</th>
<th>NAME</th>
<th>NUMBER</th>
<th>PLACE</th>
<th>DESCR</th>
<th>ACTION</th>
</tr>";
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result))
{
$output .= "
<tr>
<td>".$row['id_suciastka']."</td>
<td>".$row['name_suciastka']."</td>
<td>".$row['number_suciastka']."</td>
<td>".$row['place_suciastka']."</td>
<td>".$row['descr_suciastka']."</td>
<td><button type='button' name='delete_btn' data-id3='".$row['id_suciastka']."' class='btn btn-danger btn_delete'>Delete</button></td>
</tr>";
}
}
$output .= "</table>
</div>";
echo $output;
Let's debug this code step by step :
First of all, we should check the content of $_POST in your PHP code :
die(var_dump($_POST)); at the top of delete.php.
Do you see your id?
If yes, then... Just be sure you typed the right index name :)
If no, we have to get closer to the browser :
Open your code inspector (Ctrl+Maj+I on chrome), get to the Network panel. When you fire your AJAX query, a new line will apper! Just click on it, you will find in the "Headers" section all data about request/Response, and at the bottom you'll find the data you sent!
Do you see your id?
If yes, then there is code you didn't show us that do whatever something that erase your data or something ^^
If no, let's take a look in the javascript :
Still in the Inspector, open the "source" pannel and find your index.php, and more precisely the code you sent us.
Just add a marker after your var id = ... by clicking on the line numbers.
Fire your ajax request again. You will be able to see your value of id.
Is the value correct? If yes... well boy, we have to keep digging together!
If no (it is "undefined" or "null"), then that's why the browser doesn't send it!
In this case, you have to check the value of $row['id_suciastka'], for exemple by using a var_dump($row); at the begining of your loop in index.php.
If nothing seems to work, then we have to get more informations on the problem!
Hope it helps! :)
I think your button is not in the DOM
You can try:
$(document).on('click', '.btn_delete', function() {})
$('.btn_delete').on('click', function(){
var id = $(this).data("id3");
if (confirm('Naozaj zmazat ?'))
{
$.ajax({
url: 'delete.php',
method: 'POST',
data: {delete:1, id:id},
success: function(data){
alert(data);
fetch_data();
}
});
}
});
Replace type with Method in ajax request.
For start, you can console.log id before you send a post request, so try
$('.btn_delete').on('click', function(){
var id = $(this).data("id3");
console.log(id); // <-- log ID here
if (confirm('Naozaj zmazat ?'))
{
$.ajax({
url: 'delete.php',
type: 'POST',
data: {delete:1, id:id},
success: function(data){
alert(data);
fetch_data();
}
});
}
});
If you get something there, then hit F12 in Chrome or Firefox and in dev tools, go to network tab and inspect http request to your PHP and in "headers" tab check "Form data" section of request (body of http request).
If you get ID and delete properties there, then your JS is correct and you should look for bug in PHP.
Best way to start on that would be to var_dump whole $_POST array. So:
var_dump($_POST);
if (isset($_POST['delete'])) {
include("db.php");
$id = mysqli_real_escape_string($conn, $_POST['id']);
$sql = "DELETE FROM suciastka WHERE id_suciastka = '".$id."'";
if (mysqli_query($conn, $sql))
{
echo "Deleted";
}
}

Deleting a row using AJAX using fadeOut

I am following a tutorial online on AJAX. There is a lecture on how to delete a row from a table without reloading it again.
I added a delete button for each row in my HTML table and I set its id to id="del" inside a table with an id="myTable".
I am trying to delete a row using Ajax and remove it without refresh with an animation fadeOut().
I have this Ajax script:
$("#myTable #del").click(function()
{
if(confirm("Are you sure you want to delete this row ?"))
{
var id = $(this).closest('tr').attr('id');
var row = $(this).closest('tr');
$.ajax
({
url: 'delete_row.php',
type: 'POST',
data: {dataID: id},
dataType: "text",
success:function(data)
{
console.log(id);
if(data=="deleted")
{
row.fadeOut('slow', function() {$(this).remove();});
}
}
});
}
});
In the console, I see the correct id displayed, but neither does it disappear from the table nor get deleted from database.
Here is the PHP code:
try
{
$id = $_POST['dataID'];
$delete = "DELETE FROM employee WHERE id = :d";
$delStmt = $conn->prepare($delete);
$delStmt->bindValue(":id", $id);
$delStmt->execute();
echo "deleted";
}
catch(PDOException $m)
{
$m->getMessage();
echo "error";
}
The instructor code is working properly, and I can't see where my error is so it isn't working for me. Any help is appreciated.
Bind value hasn't same name in the PDO request
$delete = "DELETE FROM employee WHERE id = :d";
$delStmt->bindValue(":id", $id);

AJAX for successful php :: delete checked table list :: using hyperlink NOT input

Project Focus: Delete Multi-checked table list from form.
Specs:
1.) Delete actioned by using <a href> hyperlink (NOT <input type="submit"
2.) I'd like to action this with AJAX, including confirm & error/success responses.
Status of Delete Action: I've finally got my code working to delete multi-checkboxes. See the successful PHP Code Snippet below.
Note: the successful $_POST coding is currently being handled in the same page by using <input type="submit" name="delete>".
I've tried to get it to work, but no luck. Could someone please have a look through the coding & script to see if you can spot any errors?
My thoughts (but uncertain):
1) the ajax var formData is written wrong to achieve getting both $delete = $_POST['delete']; and $chkbx = $_POST['chkbx'];
2) Instead of .click for <a href"#" id="#btn_del" should maybe try for using .post
Form
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" name="recordsForm" id="recordsForm">
Button
UPDATED (for spec#1) updated the href to href="deleteRecord.php"
<li class="button" id="toolbar-del">
<a href="#" title="Delete" id="btn_del">
<span class="icon-16-delete dead"></span>
Delete
</a>
</li>
PHP Code Snippet:
This code is currently included at the bottom of the form. Later, I would like to move it as a function to a separate actions.php page that will include additional button actions (edit, duplicate, archive, etc). For now, I'll be happy to just move it to deleteRecord.php page & call it with this AJAX.
<?
// Check if DELETE button active, start this
$delete = $_POST['delete'];
$chkbx = $_POST['chkbx'];
if($delete){
for($i=0;$i<$count;$i++){
$del_id = $chkbx[$i];
$sql = "DELETE FROM ".ID_TABLE." WHERE unit_id='".$del_id."'";
$result = mysqli_query($dbc,$sql);
}
// if successful redirect to delete_multiple.php
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=records_manager.php\">";
}else{
echo "Error: No luck";
}
}
mysqli_close($dbc);
?>
ajaxDELETE
// ajaxDelete.js
$(document).ready(function() {
// When TRASH button is clicked...
$('#btn_del').click(function(event) {
e.preventDefault(); // stop the form submitting the normal way
// and refreshing the page
// Get the form data // there are many ways to get this data using jQuery
// ---------------------------------- // (you can use the class or id also)
var formData = {
'chkbx' : $('input[name=chkbx]').val(),
'count' : $count[0]
// Process the form
// ================
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use
url : 'deleteRecord.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the .done(),
// promise callback
.done(function(data) {
window.console.log(data); // log data to the console so we can see
// Handle ERRORS
if ( ! data.success) {
if (data.errors.chkbx) {
$('.Records_Found').addClass('has-error');
$('.Records_Found').append('<div class="help-block">'+ data.errors.chkbx + '</div>');
}
} // end if ERRORS
else {
$('.Records_Found').append('<div class="alert alert-success" id="valid_success">'+ data.message + '</div>');
// After form submission,
// redirect a user to another page
window.location = 'records_manager.php';
}
})
.fail(function(data) { // promise callback
window.console.log(data); }); // show any errors in console
// NOTE: it's best to remove for production
event.preventDefault(); // stop the form from submitting the normal way
// and refreshing the page
}); // end submit button
}); // end document ready
deleteRecord.php
<?php
// FUNCTION to DELETE
// ===========================
// :checked existing unit data
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if ( empty($_POST['chkbx'])) // if empty, populate error
$errors['chkbx'] = 'No items have been checked yet.';
// ERROR! Return a response
if ( ! empty($errors)) {
$data['success'] = false; // any errors = return a success boolean of FALSE
$data['errors'] = $errors; // return those errors
} else {
// NO ERROR... Carry on // Process the form data
require_once('config.php'); // Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die ('Error connecting to MySQL server.'.$dbc);
// Check if DELETE
$delete = $_POST['delete'];
$chkbx = $_POST['chkbx'];
$count = $_POST['count'];
if($delete){
for($i=0;$i<$count;$i++){
$del_id = $chkbx[$i];
$sql = "DELETE FROM ".ID_TABLE." WHERE unit_id='".$del_id."'";
$result = mysqli_query($dbc,$sql);
}
// if successful redirect
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=records_manager.php\">";
}else{
echo "Error: No luck";
}
}
mysqli_close($dbc); // close DB connection
}
$data['success'] = true; // show a message of success
$data['message'] = 'Success!'; // and provide a true success variable
}
echo json_encode($data); // return all our data to an AJAX call
} // end else NO ERRORS, process form
?>
Digging through loads of bookmarks, I'd found an example of what I was hoping to achieve. After fiddling with snippets of codes, I've finally gotten the ajax to work as I'd hoped to achieve for this step of the project.
To hopefully assist others in their search for this, below, I've provided all coding for both ajax/jq/js & php that worked flawlessly in my tests.
How this code works
The button (a hyperlink outside of the form, NOT an input button) is linked to the deletedRecord.php, but the script overrides the link with e.preventDefault()
JQ is used to build the array of checked row IDs & send them to deletedRecord.php via AJAX
deleteRecord.php explodes the array, counts the total number of checked IDs, and finally loops through the query to delete each.
Upon successful completion, a response of 1 is echo'd back to trigger the success action
Hope this helps someone out there. If anyone sees any other faults I might've missed, please feel free to share for the greater good. Cheers.
ajaxDelete.js
Notes:
1.) Updated the image (button) href to href="deleteRecord.php"
2.) Researched & found a better approach that reduced the count to only the checked (I thought this would be more effective (faster) in case the table grew to a large number of rows.
$(document).ready(function() {
$('#btn_del').click(function(e) {
e.preventDefault();
page = $(this).attr("href");
ids = new Array()
a = 0;
$(".chk:checked").each(function(){
ids[a] = $(this).val();
a++;
})
// alert(ids);
if (confirm("Are you sure you want to delete these courses?")) {
$.ajax({
url : page,
type : "POST",
data : "id="+ids,
dataType : 'json',
success : function(res) {
if ( res == 1 ) {
$(".chk:checked").each(function() {
$(this).parent().parent().remove();
}) // end if then remove table row
} // end if res ==1
} // end success response function
}) // end ajax
} // end confirmed
return false;
}); // end button click function
}); // end doc ready
deleteRecord.php
<?php
require_once('config.php'); // Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die ('Error connecting to MySQL server.'.$dbc);
$del_id = explode(",",$_POST['id']);
$count = count($del_id);
if (count($count) > 0) {
foreach ($del_id as $id) {
$sql = "DELETE FROM ".ID_TABLE."
WHERE unit_id='" . $id . "'";
$result = mysqli_query($dbc,$sql)
or die(mysqli_error($dbc));
} // end for each as
mysqli_close($dbc); // close MySQL
echo json_encode(1); // Return json res == 1
// this is used for the SUCCESS action
} // end if count > 0
?>

Catch Ajax data variables in PHP?

I'm trying to get the data used below to be caught in my alives.php page.
Essentially, alives.php requires a variable $passcode.
How do I pass the content of data below as the variable $passcode through a POST request?
<script>
$(document).ready(function() {
$('#alive').click(function () {
var data = '<?php $row['code']; ?>';
$.ajax({
type:"GET",
cache:false,
url:"alives.php",
data:data, // multiple data sent using ajax
success: function (html) {
}
});
return false;
});
});
</script>
alives.php
<?php
require("database.php");
$checkvote = "SELECT code FROM votes WHERE code = '$passcode'";
$updatealive = "UPDATE votes SET alive = +1 WHERE code = '$passcode'";
$addvote = "INSERT INTO votes (code, alive) VALUES ('$passcode',+1 )";
$checkvoterlt = mysqli_query($con, $checkvote);
if(mysqli_num_rows($checkvoterlt) > 0) {
$result = mysqli_query($con, $updatealive) or die(mysqli_error());
} else {
$result = mysqli_query($con, $addvote) or die(mysqli_error());
}
mysqli_close($con);
?>
So much is wrong.
Problem 1: You are specifying a GET request: $.ajax({ type:"GET",. If you want it to be POST:
$.ajax({
type:"POST",
Problem 2: Your javascript data variable should be key: value pairs like:
var data = { 'passcode' : code };
Then in PHP get the data with $_POST['passcode']
This sort of passcode should NOT be passed to the client side, as it can be easily manipulated.
Instead, store such information in a $_SESSION variable (assumes you've started your PHP with session_start), as this will keep the value safe, pass it to all pageloads where it may be needed, and be impossible to manipulate (while it is possible to hijack someone else's session, a malicious user still won't be able to actively change the value)

Passing a Jquery variable to use in a PHP script

I know I've asked this question before but I still need help with this, basically:
I have a booking grid as shown below which is on bookings.php
On this booking grid I have a dblClick event:
ondblClickRow: function(rowid)
{
rowData = $("#bookings").getRowData(rowid);
var brData = rowData['bookref'];
getGridRow(brData);
$("#cp-bookings-dialog").dialog({ hide: 'slide', height: 625, width: 733, title: 'Booking Reference: - '+ brData});
},
This also opens a Jquery Dialog window on bookings.php:
<div class="cp-tiles-wrapper-dlg">
<div class="cp-booking-info left">
<p class="pno-margin">Booking Date: <strong>Booking Reference is = <? echo BookingDocket::get_bookref(); ?></strong></p>
<p class="pno-margin">Return Date: <strong><? echo BookingDocket::get_bookdate(); ?></strong></p>
<p class="pno-margin">Journey: <strong></strong></p>
<p class="pno-margin">Passenger Tel: <strong></strong></p>
<p class="pno-margin">E-mail: <strong></strong></p>
</div>
</div>
Where brData is the 'Booking Reference' value that I want to use in my PHP script. At the moment this dblClick event is being sent to the following Ajax request:
function getGridRow(brData) {
$.ajax({
url: 'scripts/php/bootstrp/all.request.php',
type: 'POST',
data: {
fnme: 'getDGRow',
rowdata: brData,
id: null,
condition: null
},
dataType: 'text/xml',
timeout: 20000,
error: function(){
alert("It failed");
$('#cp-div-error').html('');
$('#cp-div-error').append('<p>There was an error inserting the data, please try again later.</p>');
$('#cp-div-error').dialog('open');
},
success: function(response){
// Refresh page
//response = brData;
//alert(response); <-- This alerts the correct Booking Reference value
}
});
Which gets sent to all.request.php
// Switch to determine method to call
switch ($_REQUEST['fnme']) {
case 'getDGRow':
header('Content-type: text/xml');
GetBookings::getGridRow($_REQUEST['rowdata']);
break;
And finally to the PHP script where I want to use this Jquery value:
class GetBookings {
public static function getGridRow($rowdata) {
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
try {
$query = "SELECT * FROM tblbookings WHERE bookref = '$rowdata'";
//echo $query; <-- this passes the correct Booking Reference to £rowdata
$stmt = $dbh->prepare($query);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_BOTH);
BookingDocket::set_id($row['id']);
BookingDocket::set_bookref($row['bookref']);
BookingDocket::set_bookdate($row['bookingdate']);
BookingDocket::set_returndate($row['returndate']);
BookingDocket::set_journeytype($row['journeytype']);
BookingDocket::set_passtel($row['passengertel']);
BookingDocket::set_returndate($row['returndate']);
$stmt->closeCursor();
}
catch (PDOException $pe) {
die("Error: " .$pe->getMessage(). " Query: ".$stmt->queryString);
}
$dbh = null;
}
}
?>
I'm not sure why, but this doesn't seem to be working. Basically at the time when the Jquery Dialog window is opened, $rowdata is null, but when I echo the query, it shows that $rowdata has the correct value.
I have tried putting the code for the jquery window into a seperate php file and in the sucess ajax script I have added the following:
$('#cp-bookings-dialog').load('bookings-dialog.php', function() {
alert('Load was performed.');
});
but this doesn't make any difference. I know all the code is correct because if I set $rowdata to 'BR12345' for example, it displays the values I need in the jquery booking dialog. What I believe needs to be done is for the PHP query to run after the value $rowdata has been passed to the PHP script.
Anybody got any idea of how I can do this?
You need to return a JSON encoded object from your PHP script to use in your pop up. Your echo call is evaluated before the AJAX call is made, and worse, it does not know about GetBookings state at all (the state is only valid for a single request).
And why is everying static? That looks like a bad software design.

Categories