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

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.

Related

How to get the checkbox value in php html

I have a table showing database values as shown here:
<?php
while ($single = $output->fetch_assoc()):?>
<tr>
<td> <?php echo $single['Dptname']; ?></td>
<td> <?php echo $single['firstname']; ?> </td>
<td> <?php echo $single['lastname']; ?> </td>
<td> <?php echo $single['email']; ?> </td>
<td> <?php echo $single['phnumber']; ?> </td>
<td> <?php echo $single['provider']; ?> </td>
<td style="display: none"> <?php echo $single['id']; ?></td>
<td><input type="checkbox" class="Dptadmin" id="Dptadmin" value="1"></td>
<td><input type="checkbox" class="superuser" id="superuser" value="1"></td>
<td><button type="button" class="btn b1 editbtn" data-toggle="modal" value="" data-target="#myModal"> <i class="fa fa-pencil-square-o"> </i> </button>
<i class="fa fa-trash-o"></i>
</td>
</tr>
<?php endwhile;?>
jQuery:
<script>
$(document).ready(function (){
$('.editbtn').on('click', function(){
$('#editmodal').modal('show');
$tr = $(this).closest('tr');
var data = $tr.children('td').map(function(){
return $(this).text();
}).get();
console.log(data);
$('#Dptname').val(data[0]);
$('#firstname').val(data[1]);
$('#lastname').val(data[2]);
$('#email').val(data[3]);
$('#phnumber').val(data[4]);
$('#provider').val(data[5]);
$('#userid').val(data[6]);
$('#userid').val(data[6]);
$('#Dptadmin').val(data[7]);
});
});
Tried:-
$('.Dptadmin').on('click', function(){
$tr = $(this).closest('tr');
var data = $tr.children('td').map(function(){
return $(this).text();
}).get();
console.log(data);
$('#userid').val(data[6]);
var val = $(this).find(":checkbox['<?php echo $single['Dadmin']; ?>']").val();
console.log(val);
As above jQuery, from console.log(data) I'm getting the value of selected TD, but not getting checkbox value. Thank you in advance.
if you only want to get the value of your checkbox when it is clicked then use the below code
$('.Dptadmin').on('click', function(){
console.log($(this).val());
});
I got the solution on my own. thank you for your support your ideas are made me think beyond. here is my solution.
$('.Dadmin').on('click', function(){
$tr = $(this).closest('tr');
var data = $tr.children('td').map(function(){
return $(this).text();
}).get();
var userid = data[6];
var admin = $('#Dadmin').val();
$.ajax({
type: 'POST',
url: 'makeadmin.php',
data: {
userid : userid,
admin : admin,
},
success: function(data){
console.log(data.length);
},
});
})
html
<tr>
<td> <?php echo $single['Dptname']; ?></td>
<td> <?php echo $single['firstname']; ?> </td>
<td> <?php echo $single['lastname']; ?> </td>
<td> <?php echo $single['email']; ?> </td>
<td> <?php echo $single['phnumber']; ?> </td>
<td> <?php echo $single['provider']; ?> </td>
<td style="display: none"> <?php echo $single['id']; ?></td>
<td><input type="checkbox" class="Dadmin" id="Dadmin" value="1"></td>
<td><input type="checkbox" class="superuser" id="superuser" value="1"></td>
<td><button type="button" class="btn b1 editbtn" data-toggle="modal" value="" data-target="#myModal"> <i class="fa fa-pencil-square-o"> </i> </button>
<i class="fa fa-trash-o"></i>
</td>
</tr>
here only i changed $('#userid').val(data[6]); to var userid = data[6];
hope so this will help somebody. thank you all once.

Simple ajax function send NULL id

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

How to reload Datatable without refreshing the page?

I'm sorry my English is week. Please tell me the process to reload data without refreshing the page using datatable jquery. My reload table was not working.
my view is :
<table id="table_id" class="table table-striped table-hover table-bordered" cellspacing="0" width="100%">
<thead>
<tr style="background-color:#1c2d3f;color:white;">
<th>Kategori <span style="padding-top:5px;font-size:12px;" class="hidden-sm hidden-xs pull-right glyphicon glyphicon-sort"></span></th>
<th>Deskripsi <span style="padding-top:5px;font-size:12px;" class="hidden-sm hidden-xs pull-right glyphicon glyphicon-sort"></span></th>
<th style="width:200px;">Tipe Kategori <span style="padding-top:5px;font-size:12px;" class="hidden-sm hidden-xs pull-right glyphicon glyphicon-sort"></span></th>
<th>Slug <span style="padding-top:5px;font-size:12px;" class="hidden-sm hidden-xs pull-right glyphicon glyphicon-sort"></span></th>
<th>Aktif <span style="padding-top:5px;font-size:12px;" class="hidden-sm hidden-xs pull-right glyphicon glyphicon-sort"></span></th>
<th>Opsi</th>
</tr>
</thead>
<tbody>
<?php foreach($data_kategori as $ambil_data){?>
<tr>
<td style="background-color:white;"><?php echo $ambil_data->kategori;?></td>
<td style="background-color:white;"><?php echo $ambil_data->deskripsi;?></td>
<td style="padding-top:15px;background-color:white;"><?php
if($ambil_data->parent_kategori == "0"){
echo "<label class='label label-primary'>Kategori Utama</label>";
}else{
echo "<label class='label label-default'>Anak kategori</label>";
}?>
</td>
<td style="background-color:white;"><?php echo $ambil_data->slug;?></td>
<td style="padding-top:15px;background-color:white;"><?php
if($ambil_data->aktif == "Y"){
echo "<label class='label label-success'>Aktif</label>";
}elseif($ambil_data->aktif == "N"){
echo "<label class='label label-danger'>Tidak aktif</label>";
}?>
</td>
<td style="background-color:white;">
<i class="glyphicon glyphicon-pencil"></i>
<i class="glyphicon glyphicon-remove"></i>
</td>
</tr>
<?php }?>
</tbody>
When insert data this my jquery :
function reload_table(){
table.ajax.reload(null,false); //reload datatable ajax
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('admin/kategori/proses_tambah_kat ')?>";
}
else
{
url = "<?php echo site_url('index.php/book/book_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
Is there anything, i am doing wrong ??
You can reload Datatable by id like this
$('#table_id').DataTable().ajax.reload(null, false);
or
TableVar.ajax.reload();
It will work if you are using AJAX to get data for Datatable.
for more info see this link

Update content in HTML table using PHP and AJAX

I am trying to update the contents of the table by pressing the update button in PHP using the MySQL connection. I want to combine Ajax and PHP, because by using that I don't have to refresh the page every time.
I don't have any idea to do this. And I haven't found anything on the internet. So I came here to ask.
Here you see a picture of how my current page looks like.
My table
The code I use to generate/populate the table:
<div class="col-md-12">
<h3 class="title">Active Tasks</h3>
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>Task</th>
<th>Predecessor</th>
<th>Dev</th>
<th>MOSCOW</th>
<th>Plan</th>
<th>Do</th>
<th>Check</th>
<th>Act</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($conn, $SQL);
while ($row = mysqli_fetch_array($query)) {?>
<tr class="active">
<td style="display:none;><?php echo $row['ID'];?></td>
<td style="display:none;"><?php echo $row['ProjectID'];?></td>
<td><?php echo $row['Task'];?></td>
<td><?php echo $row['Predecessor'];?></td>
<td><?php echo $row['Dev'];?></td>
<td><?php echo $row['MOSCOW'];?></td>
<td class="js-Task-Plan"><?php echo $row['Plan'];?></td>
<td class="js-Task-Do"><?php echo $row['Do'];?></td>
<td><?php echo $row['Check'];?></td>
<td><?php echo $row['Act'];?></td>
<td>
<button type="button" class="js-TimerStart btn btn btn-default">Start</button>
<button type="button" class="js-TimerPauzeer btn btn-default">Pauzeer</button>
<button type="button" class="js-TimerResume btn btn-default">Resume</button>
<a class="btn btn-default btn-info" href="editTask.php?TaskID=<?php echo $row['ID'];?>&projectid=<?php echo $ID;?>">Aanpassen</a>
<a class="btn btn-default btn-danger" href="delete_task.php?TaskID=<?php echo $row['ID'];?>&projectid=<?php echo $ID;?>">Verwijderen</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<button class="btn btn-block btn-default btn-success" name="UpdateTable"><span style="font-weight: bold;">Update</span></button>
</div>
Thank you for every bit of response and information.
Its not too big issue.
You have to just give some class and ids to your table row and tds.
first of all give unique ids to all rows, in your case you have
<?php echo $row['ID'];? and give same class to all rows these will use later steps.
and give data-id to each row with unique id...so
every tr may be named with <tr id='tr_<?php echo $row['ID'];?>' class='projects' data-id='<?php echo $row['ID'];?>'> and Predecessor td witl be <td id='p_<?php echo $row['ID'];?>'></td>
now i am asssuming that you want to update each project Predecessor every 3 seconds..then just you need to write ajax call for updation.
setInterval(function(){
$('.project').each(function(){
var id=$(this).data('id');
$.ajax({
url:'php_file _name_that_takes_project_id_and_get_details_from_database',
data:{id:id},
type:'POST',
sucess:function(data){
// here data is returned value by ajax php file call which takes project id and fetch Predecessor related to this id.
$('#p_'+id).html(data);
}
});
});
, 3000);
Put it in separate script:
<?php
$query = mysqli_query($conn, $SQL);
while ($row = mysqli_fetch_array($query)) {?>
<tr class="active">
<td style="display:none;><?php echo $row['ID'];?></td>
<td style="display:none;"><?php echo $row['ProjectID'];?></td>
<td><?php echo $row['Task'];?></td>
<td><?php echo $row['Predecessor'];?></td>
<td><?php echo $row['Dev'];?></td>
<td><?php echo $row['MOSCOW'];?></td>
<td class="js-Task-Plan"><?php echo $row['Plan'];?></td>
<td class="js-Task-Do"><?php echo $row['Do'];?></td>
<td><?php echo $row['Check'];?></td>
<td><?php echo $row['Act'];?></td>
<td>
<button type="button" class="js-TimerStart btn btn btn-default">Start</button>
<button type="button" class="js-TimerPauzeer btn btn-default">Pauzeer</button>
<button type="button" class="js-TimerResume btn btn-default">Resume</button>
<a class="btn btn-default btn-info" href="editTask.php?TaskID=<?php echo $row['ID'];?>&projectid=<?php echo $ID;?>">Aanpassen</a>
<a class="btn btn-default btn-danger" href="delete_task.php?TaskID=<?php echo $row['ID'];?>&projectid=<?php echo $ID;?>">Verwijderen</a>
</td>
</tr>
<?php } ?>
and call it 'table.php'.
and add js code, which will be make AJAX call to table.php and update our table
$.ajax('table.php', {
success: function(data) {
$('.table-bordered.table-condensed tbidy').html($(data));
$('#notification-bar').text('The page has been successfully loaded');
},
error: function() {
$('#notification-bar').text('An error occurred');
}
});

getting checked checkbox values and form input value using jquery ajax submit

i'm implementing an appilication in which one module contains search method, we get the list of people in table, here is the code for it.
<table class="table table-striped table-bordered table-hover" id="sample_3">
<div class="modal fade" id="sms" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Compose Sms</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Message</label>
<textarea class="form-control" rows="3" name="smsmessage"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn blue">Send Sms</button>
<button type="button" class="btn default" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<thead>
<tr>
<th class="table-checkbox"> <input type="checkbox" class="group-checkable" data-set="#sample_3 .checkboxes"/></th>
<th>Surname</th>
<th>Name</th>
<th>Gender</th>
<th>Town</th>
<th>Mobile No</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
if($numrows!= "0") {
while($result = mysql_fetch_array($query,MYSQL_ASSOC)){
?>
<tr class="odd gradeX">
<td><input type="checkbox" class="checkboxes" value="<?php echo $result['mobileNo'];?>" name="numbers"/></td>
<td><?php echo $result['surname']; ?></td>
<td><?php echo $result['name']; ?></td>
<td><?php echo $result['sex']; ?></td>
<td><?php echo $result['preTown']; ?></td>
<td><?php echo $result['mobileNo']; ?></td>
<td><i class="fa fa-search"></i> View <i class="fa fa-edit"></i> Edit &nbsp<a class="fancybox-button fancybox.iframe btn btn-xs purple" href="singlesms.php?number=<?php echo $result['mobileNo'];?>"><i class="fa fa-envelope"></i> Send Sms</a></td>
</tr>
<?php
}
} else {
?>
<tr>
<td>No Records Found</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<?php
}
?>
</tbody>
</table>
now if i click submit button, i want only those values to be sent which are selected by checkbox. i want the checkbox values and input:smsmessage to be sent through jquery ajax submit. i have implemented a code but it just uses the checkbox values, i want the input value to be passed through ajax post. here is the what i have implemented
$('.btnadd').click(function(){
var checkValues = $('input[name=numbers]:checked').map(function()
{
return $(this).val();
}).get();
$.ajax({
url: 'loadmore.php',
type: 'post',
data: { ids: checkValues },
success:function(data){
}
});
});
Can u please suggest how to send the input:smsmessage also to this post method.
here is the bulksms.php
$success="0";
$message=$_POST['smsmessage'];
if($message="")
{
echo "Please Provide Details Correctly";
}
foreach($number as $_POST['numbers'])
{
$parameters['mobilenumber']=$number;
$parameters['message'] = $message;
if(api_connect("demo","demo#123",$parameters))
{
$success="1";
}
}
if($success=="1")
{
echo "SMS Sent to all selected people";
}
I'd look at pushing the value onto the end of the checkValues array, like this:
$('.btnadd').click(function(){
var checkValues = $('input[name=numbers]:checked').map(function(){
return $(this).val();
}).get();
checkValues.push( $('input[name=smsmessage]').val() );
$.ajax({
url: 'loadmore.php',
type: 'post',
data: { ids: checkValues },
success:function(data){ }
});
});
Or you could add another data value in the ajax call:
$('.btnadd').click(function(){
var checkValues = $('input[name=numbers]:checked').map(function(){
return $(this).val();
}).get();
$.ajax({
url: 'loadmore.php',
type: 'post',
data: { ids: checkValues, smsmessage: $('input[name=smsmessage]').val() },
success:function(data){ }
});
});
$('.btnadd').click(function(){
checked = $('input[name=numbers]:checked');
if( checked.length > 0 ) {
var checkValues = checked.map(function(){
return $(this).val();
}).get();
$.ajax({
url: 'loadmore.php',
type: 'post',
data: { ids: checkValues },
success:function(data){ }
});
}else{
alert("You need to pick at least one checkbox!");
}
});

Categories