Delete data from table with AJAX and PHP - 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";
}
}

Related

AJAX Call Return PHP Value Empty

i have a problem about ajax call, i dont get what exactly why i still getting this empty success call. i tried the past solution to solve this but i don't know what the cause of this.
as you can see this my table then when i click the action of update, delete, or, add, even print_r($_POST) it's still empty.
then when i go to console i got this error.
the value of selected attr still send to the php file
heres my code :
$(document).on('click', '.update', function(){
var user_ID = $(this).attr('id');
$.ajax({
url:"datatable/account/fetch_single.php",
method:"POST",
data:{user_ID:user_ID},
dataType:"json",
success:function(data)
{
console.log(data);
$('#account_modal').modal('show');
$('#username').prop("disabled", true);
$('#username').val(data.user_Name);
$('#email').val(data.user_Email);
$('#pass').val(data.user_Pass);
$('#con_pass').val(data.user_Pass);
$('#level').val(data.level_ID).change();
$('#status').val(data.user_status).change();
$('#action').val('Edit');
$('#operation').val('Edit');
$('.modal-title').text('Edit Account Info');
$('#user_ID').val(user_ID);
}
})
});
fetch_single.php
include('db.php');
include('function.php');
if(isset($_POST["user_ID"]))
{
$output = array();
$statement = $conn->prepare(
"SELECT * FROM `user_accounts`
WHERE user_ID = '".$_POST["user_ID"]."'
LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["level_ID"] = $row["level_ID"];
$output["user_Name"] = $row["user_Name"];
$output["user_Pass"] = decryptIt($row["user_Pass"]);
$output["user_Email"] = $row["user_Email"];
$output["user_status"] = $row["user_status"];
}
echo json_encode($output);
}
or it's might be the cause of problem is the design template?
i solve this issue, in my requested php file i change my $_POST to $_REQUEST if your data in ajax look like
data:{user_ID:user_ID}
or
data: "fname="+fname+"&lname="+lname
this might work for you, then if your data look like this data:new FormData(this) maybe you should use this type
data:{user_ID:user_ID}
to work the request and execute your sql.
but the best solution i got is change your
method:"POST"
to
type:"POST"
to solve this problem.
if your data.success_variable is undefined add
header('Content-type: application/json.');
to your requested php file.
Related topic:
ppumkin5 answer to
JQuery Ajax is sending GET instead of POST

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);

Why can't i see php call in Mozilla's Net tab?

$('#registerForm').submit(
function()
{
event.preventDefault();
callAjaxSubmitMethod(this);
}
);
function callAjaxSubmitMethod(form)
{
$.ajax({
type: "POST",
url: "lib/registration_validate.php",
data: $("#registerForm").serialize(),
dataType: 'json',
success: function(response)
{
console.log("cominggggg");
alert("s"+response.status);
},
error:function(response)
{
alert("e"+response.status);
},
complete:function(response)
{
console.log("Completed.");
}
});
}
This is how i am sending data to my php page.
<?php
include 'configdb.php';
session_start();
global $connection;
echo "oops";
if(isset($_POST['submit']) && $_POST['email']!='' && $_POST['password']!='')
{
$email= $_POST['email'];
$sql1 = "SELECT * FROM Users WHERE emailID = '$email'";
$result1 = mysqli_query($connection,$sql1) or die("Oops");
$response = array();
if (mysqli_num_rows($result1) > 0)
{
$response['status']='Email Already Exists';
echo json_encode($response);
exit;
}
}?>
I am just processing for duplicate email registration. If ia run this code in my chrome, i can see php in net tab. I can see completed in console and e200 in alert.
In my mozilla browser, i don't get any console strings, alerts. I din't get php page call in Net tab too.
I just cleared cache too. So it's not coming from cache too. I cleared localStorage due to out of memory error in my mozilla.
I don't even understand this behaviour. No idea to how to debug further.
I changed your code a bit, it seems that chrome accept the way you have made it, firefox does not.
So instead of this:
$('#registerForm').submit(
function()
{
event.preventDefault();
callAjaxSubmitMethod(this);
}
);
Do this:
$('#registerForm').on('submit', function(event) {
event.preventDefault();
callAjaxSubmitMethod(this);
}
);
Notice I added also the event param, you were missing that.

Ajax update table with php content

How to make an animated table only animate when a new record is added to the database.
Ajax/Js (in index.php):
$.ajax({
url : 'Not sure what goes here?',
data : {Not sure what goes here?},
dataType : 'application/json', // Is this correct?
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
var newitem = function(response){
var item = $('<div>')
.addClass('item')
.css('display','none')
.text(response)
.prependTo('#scroller')
.slideDown();
$('#scroller .item:last').animate({height:'0px'},function(){
$(this).remove();
});
}
My php (latest.php):
include ('db.php');
$sql2 = "SELECT * FROM `feed` ORDER BY `timez` DESC";
$res2 = mysql_query($sql2) or die(mysql_error());
while($row3 = mysql_fetch_assoc($res2)){
$user = $row3['username1'];
$action = $row3['action'];
$user2 = $row3['username2'];
echo ''.$user.''.$action.''.$user2.'<br>'; // Needs to be a json array?
I can't get this to work, here's how the table operates http://jsfiddle.net/8ND53/ Thanks.
$.ajax({
url : your_php_file.php',
data : {data you'r going to send to server}, // example: data: {input:yourdata}
success: function(response) {
$('#table_id').append('<tr>'+response+'</tr>'); // response is the date you just inserted into db
}
});
in your_php_file.php:
add the item into db
echo that inserted data # if you echo, then you can catch this with ajax success function then you append it into your table.
try to fill as below:
$.ajax({
type: "post"
url : 'locationOfphpCode/phpCode.php',
data : {data you want to pass}, //{name: "dan"}
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
in your php code you need to receive the data you have passed from the ajax call:
<?php
$name = $_POST['name'];
...
?>
you may add some validations in your php code.
hope this will help you.
the example you have given is using setInterval(newitem, 2000)
so you have to call ajax function on some fixed interval.

jQuery ajax delete script not actually deleting

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.

Categories