I want to add a delete button to this table, to delete the query from Database. I have the Ajax and PHP codes here :
<?php
require_once 'dbconfig.php';
$stmt = $pdo->prepare("SELECT * FROM test");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['server']; ?></td>
<td><?php echo $row['reference']; ?></td>
<td align="center"><a id="<?php echo $row['id']; ?>" class="delete-link" href="#" title="Delete">
<img src="images/delete.png" width="20px" />
</a></td>
</tr>
<?php
}
?>
the ajax :
$(document).ready(function(){
/* Data Delete Starts Here */
$(".delete-link").click(function()
{
var id = $(this).attr("id");
var del_id = id;
var parent = $(this).parent("td").parent("tr");
if(confirm('Sure to Delete ID no = ' +del_id))
{
$.post('delete.php', {'del_id':del_id}, function(data)
{
parent.fadeOut('slow');
});
}
return false;
});
/* Data Delete Ends Here */
});
delete.php :
<?php
include_once 'dbconfig.php';
if($_POST['del_id'])
{
$id = $_POST['del_id'];
$stmt=$db_con->prepare("DELETE FROM test WHERE id=:id");
$stmt->bindParam(':id', $id);
$stmt->execute();
}
?>
The row selected doesn't seem to get DELETED in the DB ... i have no error too.
You had pass data incorrectly . Please try this
$(document).ready(function()
{
$('table#delTable td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "view.php",
data: {id:id},
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
});
Related
Apologies if this question has been asked previously.
I am currently generating a basic table using PHP and have one cell where a user can add a comment.
When the user types a comment into the editable cell it saves it to the database table "TechComment column".
I want the editable cell to "disable editing" after the user entered the comment.
My code below:
Table Code
require_once "../linkd.php";
$sql = "select * from DispatchTech where Technician = ? and convert(date, Inserted) = convert(date,
getdate()) order by Completed ASC, DoneWhen";
$ses = $_SESSION['Username'];
$par = array($ses);
$stmt = sqlsrv_query($conn, $sql, $par);
if($stmt){
$count = 1;
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
$id = $row['Id'];
$txt = $row['TechComment'];
?>
<tr>
<?PHP
if($row['Completed'] == NULL){
print "<td><button onclick=location.href='complete.php?Id=".$row['Id']."'>Complete</button></td>";
}
elseif($row['Completed'] != NULL){
print '<td><span align="center" style="font-size:15px;">✅</span></td>';
}
if($row['Area'] == NULL){
print "<td><button onclick=location.href='arrive.php?Id=".$row['Id']."'>On Site</button></td>";
}else{
print "<td>";
print date_format(new DateTime($row['Area']), "H:i:s");
print "</td>";
}
?>
<td><?php echo $row['TermID']; ?></td>
<td><?php echo $row['Location']; ?></td>
<td><?php echo $row['DMRef']; ?></td>
<td><?php echo $row['Error']; ?></td>
<td><?php echo $row['Description']; ?></td>
<td><?php echo date_format($row['Inserted'], "H:i:s") ?></td>
<td><div contentEditable='true' class="edit" id='TechComment_<?php echo $id; ?>'><?php echo $txt; ?>
</div> </td>
<td><?php echo $row['Timeframe']; ?></td>
</tr>
<?PHP
$count ++;
}
}
?>
Jquery/Ajax Code:
$(document).ready(function(){
$('.edit').click(function(){
$(this).addClass('editMode');
});
$(".edit").focusout(function(){
$(this).removeClass("editMode");
var id = this.id;
var split_id = id.split("_");
var field_TechComment = split_id[0];
var edit_id = split_id[1];
var value = $(this).text();
$.ajax({
url: 'update.php',
type: 'post',
data: { field:field_TechComment, value:value, id:edit_id },
success:function(response){
console.log('Save successfully');
}
});
});
});
I found this short jquery script that will do the trick but can't get it to work.
$('.edit').editable(function (value, settings) {
return value;
});
Might it be because i'm using ajax?
I am not that familiar with ajax.
Any help will be greatly appreciated.
You can achieve it by setting contentEditable to false in your ajax response, like:
$(".edit").focusout(function(){
$(this).removeClass("editMode");
var id = this.id;
var split_id = id.split("_");
var field_TechComment = split_id[0];
var edit_id = split_id[1];
var value = $(this).text();
$.ajax({
url: 'update.php',
type: 'post',
data: { field:field_TechComment, value:value, id:edit_id },
success:function(response){
console.log('Save successfully');
$('#'+id).prop('contenteditable', false );
}
});
});
I'm trying fill the table with fetched data from database by the id of selected option. Table content must change when user selects other option. Chosen plugin is working fine and select options is filled with correct values, how to give var selektas from test.php to loader.php in query where kliento_id = $idofclient?
Somehow make selektas == $idofclient so that i could use this variable in query in loader.php
My test.php:
<script type="text/javascript">
$(document).ready(function () {
$('.chosen-select').chosen();
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#.pavadinimai").on("change",function(){
var selektas = $(this).val().split('|');
$.ajax({
type: "POST",
url: "loader.php",
data: {selektas[o]},
success: function(result){
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});
</script>
<select class="chosen-select" name="pavname" id="pavadinimai">
<option selected="selected" value = "">---Pasirinkti---</option>
<?php
echo "Pasirinkite klienta";
$sql = "SELECT id, kliento_pav FROM klientai";
$stmt = mysqli_query($link, $sql);
while ($row = mysqli_fetch_assoc($stmt)) {
echo "<option value='" . $row['id'] .'|'. $row['kliento_pav'] . "'>" . $row['kliento_pav'] . "</option>";
}
list($idofclient,$pavofclient) = explode ('|',$_POST['pavname']);
?>
</select>
<div id="show">
</div>
And this is my code in loader.php
<?php
require_once "config.php";
if(isset($_POST["pavadinimas"])){
$sql_query="SELECT uzsakymai.id, kliento_id, uzsakymai.kiekis,prekes.pavadinimas,uzsakymai.aprasymas FROM uzsakymai INNER JOIN prekes ON uzsakymai.prekes_id = prekes.id INNER JOIN klientai on uzsakymai.kliento_id = klientai.id WHERE kliento_id = $idofclient"
$resultset = mysqli_query($link, $sql_query) or die("database error:". mysqli_error($link));
while( $result = mysqli_fetch_assoc($resultset) ) {
?>
<br>
<table id="data_table" class="table table-striped">
<thead>
<tr>
<th>Prekės pavadinimas</th>
<th>Kiekis</th>
<th>Aprašymas</th>
</tr>
</thead>
<tbody>
<tr id="<?php echo $result ['id']; ?>">
<td><?php echo $result ['pavadinimas']; ?></td>
<td><?php echo $result ['kiekis']; ?></td>
<td><?php echo $result ['aprasymas']; ?></td>
</tr>
</tbody>
</table>
<?php } ?>
<?php
echo $result
}
?>
I'm using ...jquery/3.1.1/jquery.min.js
Try this
Initially you initialized the table so first clear that table
$('#myTable').dataTable().fnDestroy();
Then initialize again after ajax success
$('#myTable').dataTable();
Like this.....
$(document).ready(function(){
$("#.pavadinimai").on("change",function(){
$.ajax({
type: "POST",
url: "loader.php",
data: {$idofclient},
success: function(result){
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});
$(document).ready(function() {
$("#pavadinimai").on("change", function() {
var pavadinimai = $("#pavadinimai").val();
$.ajax({
type: "POST",
url: "loader.php",
data: {
pavadinimai: pavadinimai
},
success: function(result) {
$("#show").html(result);
$('#show').dataTable().fnDestroy();
$('#show').dataTable();
}
});
});
});
I want to delete row in database without reloading the page. I have written following codes. It does delete row in page but not in database. which means connection not going to ajax. pls help.
<?php
$advances_result= mysqli_query($conn, "SELECT * FROM advances") or die("error");
?>
<table border>
<caption>ADVANCES</caption>
<tr>
<th>Date</th>
<th>EmpName</th>
<th>EmpCode</th>
<th>Amount</th>
<th>Comment</th>
<th>Action</th>
</tr>
<?php
while($row = mysqli_fetch_array($advances_result)){
?>
<tr>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['empname'];?></td>
<td><?php echo $row['empcode'];?></td>
<td style='text-align:right'><?php echo $row['amount'];?></td>
<td><?php echo $row['comment'];?></td>
<td><button class="delete" id="<?php echo $row['id']; ?>" > Delete</button></td>
</tr>
<?php
}
?>
</table>
'jquery part'
<script>
$(document).ready(function(){
$(".delete").click(function() {
if (confirm("Do you want to delete this row?"))
{
var row = $(this).parents('tr');
var id = row.attr("id");
var data = 'id=' + id ;
$.post({
type: "post",
url: "deleteadvances.php",
data: data,
cache: false,
success: function(){
row.slideUp('slow', function() {$(row).remove();});
}
});
}
return false;
});
});
</script>
'deleteadvances.php' page:
<?php
include("connection.php");
$id = $_POST['id'];
mysqli_query($conn,"INSERT INTO advancehistory SELECT * FROM advances WHERE ID='".$id."'");
mysqli_query($conn,"DELETE FROM advances WHERE ID='".$id."'");
?>
You need to test the output of mysqli_query in deleteadvances.php, if all good, it shows JSON Ok message that is easy parsable with $.post on the jQuery side.
e.g: {"deleted":"id"} on success or {"error":404} on error not found.
I think the id that you're passing from javascript to ajax is incorrect.
var data = 'id=' + id;
is appending the id with string 'id=' and now it finally becomes a string. When it is being passed to ajax, there is just a value and not a [key, value] pair. So, when you are accessing it in php you will get wrong id or Null value.
Try:
$.post({
type: "post",
url: "deleteadvances.php",
datatype : 'json',
data: {
id : id
},
cache: false,
contentType : 'application/x-www-form-urlencoded; charset=utf-8'
});
Change 'deleteadvances.php' page:
<?php
include ('connection.php');
$id=$_POST['id'];
$delete = "DELETE FROM table_name WHERE id=$id";
$result = mysqli_query($db,$delete) or die("Bad SQL: $delete");
?>
<?php
while ($row = mysqli_fetch_array($query,MYSQLI_BOTH))
{
$id= $_POST['tran_no'];;
?>
<tbody>
<tr id=<?php echo $row['trans_no']?>>
<td><?php echo $row['trans_no']?></td>
<td><?php echo $row['obj_code']?></td>
<td><?php echo $row['div_no']?></td>
<td><?php echo $row['check_no']?></td>
<td><?php echo $row['payee']?></td>
<td><?php echo $row['payment']?></td>
<td><?php echo $row['add']?></td>
<td><?php echo $row['amount']?></td>
<td><?php echo $row['amountw']?></td>
<td>
<img src="image/remove.png">
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<script src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("trans_no");
var info = 'trans_no=' + 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>
My problem is the ajax code doesnt seem to delete the row i dont know if the ajax code is executed or not. help would be much need, and please give me an insight as to what is the problem with my code or if i have to add something. heres the delete.php
<?php
$con = mysqli_connect("localhost","root"," ","dole") or die("Could not connect database");
if($_POST['trans_no'])
{
$id=$_POST['trans_no'];
$delete = "DELETE FROM table_no WHERE trans_no = '$id'";
$res=mysqli_query($con,$delete);
}
?>
OPTION 1:
You are assigning id from database to id attribute and in AJAX, reading trans_no.
trans_no attribute is not set for the delete link.
That is why you are not getting it.
Change your HTML to
<img src="image/remove.png">
To make it HTML5 Compliant:
<img src="image/remove.png">
And change JS:
var del_id = element.attr("data-id");
OPTION 2
Just change the line:
var del_id = element.attr("trans_no");
To
var del_id = element.attr("id");
And use your existing code.
It will work.
Try the below code,
$(".delete").click(function(){
var element = $(this);
var del_id = this.id;// use this.id as your database id related to element id
var info = {trans_no : del_id};
if(confirm("Are you sure you want to delete this?")){
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(data){
if(data=='success'){
// hide only in case of successful deltion
element.parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
} else {
alert('Error while deleting');
}
}
});
}
return false;
});
And in PHP return success or error like,
<?php
$con = mysqli_connect("localhost","root"," ","dole") or die("Could not connect database");
$status='error';
if(isset($_POST['trans_no']) && $_POST['trans_no']){
$id=$_POST['trans_no'];
$delete = "DELETE FROM table_no WHERE trans_no = '$id'";
$res=mysqli_query($con,$delete);
if($res){// only success in case of deleted.
$status='success';
}
}
echo $status;
?>
Try this:
$(function() {
$(".delete").click(function(){
var element = $(this);
var transNoVar = element.attr('id');
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: {
trans_no: transNoVar
},
success: function(data){
// delete.php return 1 on success 0 otherwise, check it here
if(data=='1') {
// on success hide the tr
// add class="show" to the tr
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
} else {
alert('Error deleting your record');
}
}
});
}
return false;
});
});
There is a div element :
...
<div id="liste_secteurs"></div>
...
<script type="text/javascript">
$(document).ready(function() {
rechercheSecteursEtProduits(0); // setting the div's content
$('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
});
});
function rechercheSecteursEtProduits(pn){
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_user="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html); // this is the div element
}
</script>
Code of ListerProduitsUserParSecteursAjax.php :
<?php
... // getting database data
?>
<p>Total : <?php echo $nr; ?></p>
<div><img src="<?php echo HTTP_ICON.'plus.png'; ?>" /></div>
<?php echo $paginationDisplay; ?>
<table id="table" class="data display " >
<thead style="background-color:#CCC">
<tr>
<th><?php echo _getText("service.produit.form.secteur_activite");?></th>
<th><?php echo _getText("service.produit.form.titre");?></th>
<th></th>
<th><?php if($data["secteur"]["cnt"] > 0){ ?><input type="checkbox" id="check_all"><?php }?></th>
</tr>
</thead>
<tbody style="background-color:#FFF">
<?php
if($data["secteur"]["cnt"] > 0){
for($i=0;$i<$data["secteur"]["cnt"];$i++){?>
<tr class="odd gradeX">
<td><?php echo $data["secteur"][$i]["secta_lib_fr"] ?></td>
<td><?php echo $data["secteur"][$i]["produit_lib"] ?></td>
<td align="center" style="vertical-align:middle"><img src="<?php echo HTTP_ICON.'edit.png'; ?>" alt="<?php echo _getText('main.btn.modifier'); ?>" style="height:10px;width:10px;" /></td>
<td align="center" style="vertical-align:middle"><input type="checkbox" id="prod_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_produit']; ?>"><input type="hidden" id="secteur_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_secteur']; ?>"></td>
</tr>
<?php } ?>
<?php
}
else{
?>
<tr class="odd gradeX">
<td colspan="4" align="center"><b><?php echo _getText('main.liste.no_data'); ?></b></td>
</tr>
<?php }?>
</tbody>
</table>
<?php if($data["secteur"]["cnt"] > 0){ ?>
<div align="right"><input name="btnSupprimer" id="btnSupprimer" type="button" value="<?php echo _getText("main.btn.delete"); ?>" class="btn btn-blue"/></div>
<?php } ?>
<?php echo $paginationDisplay; ?>
When the page loads for the first time then the delete button works fine : the selected rows are deleted , and the list reappears accordingly to new database data. But later when I want to delete other rows then the alert does not show when I check some checkboxes and clicking the delete button !
So what is wrong in my approach ?
From what I am reading you are having problems with the row that are added from the database.
What could be the problem is when you execute this peace of code:
$('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
When you call the $.click() function you add a event to all the existing DOM object that have a id of 'btnSupprimer', however this doesn't update if you add a new DOM object. So what you should do is call this function every time you add a new row. you would get something like this:
function rechercheSecteursEtProduits(pn){
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_user="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html);
$('#btnSupprimer').click(addClickHandler()); // this is the div element
}
function addClickHandler(){
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
}
I hope it helps
Try using on instead of click as below
$('#btnSupprimer').on("click","#liste_secteurs",function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
});
Use the dynamic jquery selector instead of the regular 'click' event
$('#liste_secteurs').on('click', '#btnSupprimer', function() {});
// $("container").on("event", "button", function() {});
As from Caveman's answer I made some updates :
function rechercheSecteursEtProduits(pn) {
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_usermer="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html);
$('#btnSupprimer').on('click',function(){
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
if (confirm("Do you want to remove these records ?")) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0);
}
}
});
}
And it works !