Simple ajax function send NULL id - php

I'm trying to make simple delete ajax function. I'm not very good ad JS at all but when I click on button delete I can see in Chrome Dev Console that id = NULL and when I refresh the page the entry is back. The ajax function is pretty simple
$("body").on("click",".remove-item",function(){
var entry_id = $(this).parent("td").data('entry_id');
var c_obj = $(this).parents("tr");
$.ajax({
dataType: 'json',
type:'POST',
url: 'delete.php',
data:{entry_id:entry_id}
}).done(function(data){
c_obj.remove();
toastr.success('Item Deleted Successfully.', 'Success Alert', {timeOut: 5000});
});
});
And the button
<button class="btn btn-danger remove-item" > Delete</button>
And this is the delete.php
$entry_id = $_POST["entry_id"];
$stmt = $pdo->prepare("DELETE FROM entries WHERE entry_id = :entry_id");
$stmt->bindParam(':entry_id', $entry_id, PDO::PARAM_INT);
$stmt->execute();
echo json_encode([$entry_id]);
Any idea what can be wrong?
update. The table
echo '<table class="table">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Transaction Quote</th>
<th>Action</th>
</tr>
</thead>';
foreach($pdo->query("SELECT * FROM entries ORDER BY entry_id DESC LIMIT 20") as $row){
echo '
<tbody>
<tr>
<td>'.$row['entry_id'].'</td>
<td>'.$row['entry_name'].'</td>
<td>'.$row['entry_transaction_quote'].'</td>
<td><button class="btn btn-sm btn-danger remove-item" ><i class="glyphicon glyphicon-trash"></i> Delete</button></td>
</tr>
</tbody> ';
}
echo ' </table>

Change your td with class name
<td class="entry_id">'.$row['entry_id'].'</td>
jquery
var entry_id = $(this).parent("td").parent("tr").find('.entry_id').text().trim();

Try this
Html should be like
<tr entry_id="<?=$row['entry_id']?>">
<td><button class="btn btn-sm btn-danger remove-item" ><i class="glyphicon glyphicon-trash"></i> Delete</button></td>
</tr>
Js code should be like
var entry_id = $(this).parent().parent().attr("entry_id");

Related

How can I retrieve the record in the table using their ID.?

I'm having trouble in retrieving records. I have a table and it contains records. I want to view the details of that record using the view button. But the problem is when I try to view the record all of the records is showing same details even though they are different in the database. I'm retriving the records using their ids. Here are my code
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Family Number</th>
<th>Age</th>
<th>Chief of Complaints</th>
<th>Diagnosis</th>
<th>Medication Treatment</th>
<th>Time Added</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php do{ ?>
<tr>
<td class="patient_id"><?php echo $row['id']; ?></td>
<td><?php echo $row['family_number']; ?></td>
<td><?php echo $row['Age'];?></td>
<td><?php echo $row['chief_complaints']; ?></td>
<td><?php echo $row['diagnosis']; ?></td>
<td><?php echo $row['medication_treatment']; ?></td>
<td><?php echo $row['added_at']; ?></td>
<td>
<div class="col-2">
<!-- view -->
view
<!-- <div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown button
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item view_btn" href="#">View</a></li>
<li><a class="dropdown-item" href="#">Edit</a></li>
</ul>
</div>
</div> -->
</td>
</tr>
<?php }while($row = $medical_itr->fetch_assoc()); ?>
</tbody>
ANd this is my js code for retrieving the data using their id
<script>
$(document).ready(function () {
$('.view_btn').click(function (e) {
e.preventDefault();
var p_id = $(this).closest('tr').find('.patient_id').text();
// console.log(p_id);
$.ajax({
type: "POST",
url: "Modals/viewHistory/view_medical_itr.php",
data: {
'checking_viewbtn': true,
'patient_id': p_id,
},
success: function (response){
// console.log(response);
$('.patient_viewing').html(response);
$('#medical_itr').modal('show');
}
});
});
});
</script>
And this is my php code for retriving data in the database
include_once("connections/connections.php");
$con = connection();
if(isset($_POST['checking_viewbtn'])){
$p_id = $_POST['patient_id'];
$sql = "SELECT * FROM medical_itr WHERE id = '$p_id'";
$medical_itr = $con->query($sql) or die ($con->error);
$row = $medical_itr->fetch_assoc();
}
This is sample pic
As you can see in the picture in the bottom left the id is 31 same as the url, but the view button I'm trying access the id in the table is 21.
my suggestion is that you pass data id in view_button and keep your row id in data id.
<a class="btn btn-primary view_btn mb-2" data-id="<?php echo $row['id'];
?>" >view</a>
then get the data id in jquery-> like this
var p_id = $(this).data('id');

How to delete multiple rows from table using Angular.js?

I'm trying to delete multi rows from table using checkbox with Angular and php ,
but i'm not able to get that to work and my knowledge with Angular stoped here !
this is my table :
<div class="table-responsive" style="overflow-x: unset;">
<button class="btn btn-danger" ng-click="deleteBulk()" >Delete</button>
<table datatable="ng" dt-options="vm.dtOptions" class="table table-bordered table-striped" >
<thead>
<tr>
<th ><input type="checkbox" ng-model="master" > select</th>
<th>date</th>
<th>first name</th>
<th>last name</th>
<th>age</th>
<th>action</th>
<th>action</th>
<th>action</th>
</tr>
</thead>
<tbody>
<tr id="<?php echo $row["id"]; ?>" ng-repeat="name in namesData " >
<td name="checkbox">
<input type="checkbox" name="arrExample"
ng-model="arrInput" ng-true-value="{{name.id}}"
ng-checked="master"
ng-click='pushInArray(name.id)'>
</td>
<td>{{name.date}}</td>
<td>{{name.first_name}}</td>
<td>{{name.last_name}}</td>
<td>{{name.age}}</td>
<td><button type="button" ng-click="fetchSingleData(name.id)" class="btn btn-warning btn-xs">edit</button></td>
<td><button type="button" ng-click="deleteData(name.id)" class="btn btn-danger btn-xs">delete</button></td>
<td><button type="button" ng-click="single_move(name.id)" class="btn btn-success btn-xs">send</button></td>
</tr>
</tbody>
</table>
and this is my Angular code :
$scope.exampleArray = [];
$scope.pushInArray = function(id) {
// get the input value
var inputVal = id;
var array = $scope.exampleArray.push(inputVal);
$scope.deleteBulk = function(){
if(confirm("Are you sure you want to delete this record?")){
$http({
method:"POST",
url:"insert.php",
data:{'id':$scope.exampleArray, 'action' : 'deleteBulk'}
}).success(function(data){
$scope.success = true;
$scope.error = false;
$scope.successMessage = data.message;
$scope.fetchData();
});
}
};
};
and this is my php code inside insert.php
if($form_data->action == "deleteBulk")
{
$query = "
DELETE FROM orders WHERE id='".$form_data->id."'
";
$statement = $connect->prepare($query);
if($statement->execute())
{
$output['message'] = 'done!';
}
}
can anyone tell me what i'm doing wrong please ?
thank you
You are deleting one row each time with a unique id. So code base is correct.
To delete multiple rows, use the checkbox in each row and user will select multiple rows to delete and then delete rows by multiple ids.
You will also need to update SQL query to delete multiple rows at a time.
Something like below
DELETE FROM orders WHERE id IN (1, 2, 3, 4, ..., 10);

How to get id from php loop in jquery

Hi I'm trying to get the id for each row shown in while loop in my jquery function
Here are the request and view (PHP code)
<div class="container">
<table class="table table-striped">
<div class="table responsive">
<thead class="black white-text">
<tr>
<th>#</th>
<th>Nom et Prénoms</th>
<th>Fonction</th>
<th>Université</th>
<th>Email</th>
<th>Contact</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$result = $connection->query($stmt) ;
if($result->rowCount() > 0)
{
while($row = $result->fetch(PDO::FETCH_BOTH))
{
echo '<tr>
<td scope="row">'.$row["id"].'</td>
<td>'.$row["nom"].'</td>
<td> '.$row["fonction"].'</td>
<td> '.$row["nomU"].'</td>
<td> '.$row["email"].'</td>
<td> '.$row["Contact"].'</td>
<td>' ?>
<button type="button" class="btn btn-success valider">Valider</button> /<button type="button" class="btn btn-danger rejeter">Rejeter</button>
<?php
echo '</td>
<td>'
?>
<input type="hidden" class="the_id" value='<?php echo $row[' id ']; ?>'>
<?php echo '</td>
</tr>';
}
}
else
{
echo "0 results";
}
?>
</tbody>
</div>
</table>
</div>
And I want to show the id of each row when I click on the button "valider" for the line with jquery but it's showing the first id for all the row.
Here is th jquery code
$(document).ready(function(){
$('.valider').click(function(e){
alert($('.the_id').val());
});
});
Almost right. Remember that when accessing by a class name rather than an ID, you will get all of those objects.
So, we need to be more specific. Give this a try:
$('.valider').click(function(e){
var id = $(this).parent().parent().find('td').find('.the_id').val();
alert(id);
});
This takes you from $(this), your button, to its parent <td>, then the parent <tr>, then looks for any classes of .the_id inside the tr, in other words, the specific one you want.
I usually add a custom attribute to the elements, like data-custom-id.
'<button type="button" class="btn btn-success valider" data-custom-id="'.$row["id"].'">Valider</button>'
And then in the calling function I can access the object with this
$('.valider').click(function(e){
alert($(this).attr('data-custom-id'));
});
You need to go up to the parent tr to get the related input so you could use closest() with the $(this) :
$('.valider').click(function(e){
alert( $(this).closest('tr').find('.the_id').val() );
});

Passing one of the <td> value to controller when clicking a button

I have a table like this:
When I click the Delete! button, I want to pass the role ID to the controller.
After looking for a lot of cases in stackoverflow. I've just succeeded to retrieve the role ID using JS.
Code like this:
$(".deleteButton").click(function() {
var $row = $(this).closest("tr");
var $text = $row.find("td:first-child").text();
// Let's test it out
alert($text);
});
But the problem is, I don't how to pass it back to the button, so then the button can pass it to the controller.
Is there any simple way to pass it to the controller? Maybe without retrieving the role ID first, and when click the button the value passed and the controller called at once?
This is my code:
<table class="table" id="myTable">
<thead class="text-primary">
<th class="col-md-1">ID Role</th>
<th class="col-md-3">Role</th>
<th class="col-md-3">Jumlah Member</th>
<th></th>
</thead>
<tbody>
<?php
foreach($result as $row) { ?>
<tr>
<td><?php echo $row->id_role ?></td>
<td><?php echo $row->role ?></td>
<td><?php echo $row->jumlah ?></td>
<td>
<button type="button" class="btn btn-success btn-sm editButton">Edit!</button>
<button type="button" class="btn btn-danger btn-sm deleteButton">Delete!</button>
</td>
</tr>
<?php
} ?>
</tbody>
</table>
Do you have to use JavaScript? If not, this is a simple task for a form
<form action="path/to/your/controller" method="post">
<table class="table" id="myTable">
<!-- thead, etc -->
<tbody>
foreach($result as $row) : ?>
<tr>
<td><?= $row->id_role ?></td>
<td><?= $row->role ?></td>
<td><?= $row->jumlah ?></td>
<td>
<button type="submit" name="edit" value="<?= htmlspecialchars($role->id_role) ?>"
class="btn btn-success btn-sm editButton">Edit!</button>
<button type="submit" name="delete" value="<?= htmlspecialchars($role->id_role) ?>"
class="btn btn-danger btn-sm deleteButton">Delete!</button>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</form>
Your controller would then receive either $_POST['edit'] or $_POST['delete'] with the role ID as the value.
If you're interested in securing your form from possible cross-site-request-forgery attacks, CodeIgniter has a built-in solution.
Otherwise, I would just add the id_role property to the button, eg
<button type="button" class="btn btn-danger btn-sm deleteButton" value="<?= htmlspecialchars($role->id_role) ?>">Delete!</button>
and in your JS
$('.deleteButton').on('click', function(e) {
var roleId = this.value
$.ajax({
url: '/roles/' + roleId, // assuming a REST API
method: 'DELETE'
}).done(function() {
alert('Deleted role ' + roleId);
})
})
You assign the role id to another <td> which is a little bit longer to get the id by jQuery. You easily get the click button id just give to an id like.
<button type="button" id="<?php echo $row->id_role ?>" class="btn btn-danger btn-sm deleteButton">Delete!</button>
and then you can easily get the specific row id
$(".deleteButton").click(function() {
var $text= $(this).attr("id");
alert($text);
});
and then you can send that id to controller by ajax.

cant delete record from database using $.ajax() function

i have list of records. i have delete button with every record and i am deleting record with $.ajax() function. but when i click on the delete button it does not delete the record from database , and when i alert data it outputs whole html page.here is code below. please help me.
html code
<tbody>
<tr class="gradeX odd">
<td class="sorting_1">2</td>
<td class=" ">test</td>
<td class=" ">test</td>
<td class="center ">0</td>
<td class="center ">Active</td>
<td class=" "><button type="button" class="btn btn-default btn-circle" name="editRecord"><i class="fa fa-pencil-square-o"></i></button>
<button type="button" class="btn btn-danger btn-default btn-circle" id="2" name="deleteRecord"><i class="fa fa-times"></i></button></td>
</tr>
<tr class="gradeX even">
<td class="sorting_1">3</td>
<td class=" ">sarees</td>
<td class=" ">contains sarres</td>
<td cl="center ">1</td>
<td class="center ">Active</td>
<td class=" "><button type="button" class="btn btn-default btn-circle" name="editRecord"><i class="fa fa-pencil-square-o"></i></button>
<button type="button" class="btn btn-danger btn-default btn-circle" id="3" name="deleteRecord"><i class="fa fa-times"></i></button></td>
</tr>
</tbody>
jquery
$(document.body).on('click', '[name="deleteRecord"]', function(){
var id= $(this).attr('id');
var parent = $(this).parent().parent();
if (confirm("Are you sure you want to delete this row?"))
{
$.ajax({
type: "GET",
url: "admin_operation.php?mode=delete_category&id="+id,
cache: false,
success: function(data)
{
alert(data);
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
php code
$mode = $_GET['mode'];
if($mode!='add_category' || $_GET['mode']!= "delete_category")
{
header('location:dashboard.php');
die;
}
if($mode=='delete_category')
{
$id=$_GET['id'];
$q=$db->query("DELETE FROM db_category WHERE category_id='".$id."'");
if($q){ echo "yes";}
else{ echo "no";}
}
You send 'url: "admin_operation.php?mode=delete_category&id="+id,' in javascript.
And, in php script you have a condition that rewrite headers and exit script.
if($mode!='add_category' || $_GET['mode']!= "**delete_category**")
{
header('location:dashboard.php');
die;
}
The next block of code
if($mode=='delete_category')
{
// ...
}
never is reached.
Hope this helps you as solution.

Categories