2

Project Link: https://databasetable-net.000webhostapp.com/

This following code correctly deletes a row in a table:

  $('#example').on('click', '.delete_btn', function () {
      var row = $(this).closest('tr');
      var data = table.row( row ).data().delete;
      console.log(data);
      alert("delete_btn clicked");
      row.remove();
    });

However, it is not permately deleting the row. If you refresh the page, the row that got 'deleted' still exists. I believe this is because I am not deleting the row out of the database. Normally in php you safely remove a row in a database with something like this:

id = mysqli_real_escape_string($con, $_GET['del']);
$stmt = $con->prepare("DELETE FROM employees WHERE id = ? LIMIT 1"); 
$stmt->bind_param('i', $id);
$stmt->execute(); 
$stmt->close();
header('location: index.php');

EDIT: Revised Code Index.php:

  (document).ready(function() {
var asc = true;
var table = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "server.php",
"type": "POST",
},

//http://live.datatables.net/xijecupo/1/edit
columnDefs: [{
targets: -1,
defaultContent: '<button type="button" class="delete_btn">Delete</button>'
}],
rowGroup: {
dataSrc: 1
}
});

$(function(){
    $(document).on('click','.delete_btn',function(){

        var del_id= $(this).closest('tr');
        var ele = $(this).parent().parent();  //removed the "$" from the ele variable. It's a js variable.
        console.log(del_id);

        $.ajax({
            type:'POST',
            url:'delete.php',
            dataType: 'json', //This says I'm expecting a response that is json encoded.
            data: { 'del_id' : del_id}, 

            success: function(data){ //data is an json encoded array.

              console.log('Data: ' + data); //Going to display whats in data so you can see whats going on.

              if(data['success']){  //You are checking for true/false not yes or no.
                console.log('You successfully deleted the row.');
                alert("delete btn clicked");
                ele.remove();
              }else{
                console.log('The row was not deleted.');
                }

             }

            });
        });
}); //http://jsfiddle.net/zfohLL0a/

}); //end doc ready

delete.php code:

$del_id = $_POST['del_id']; 
$stmt = $conn->prepare("DELETE FROM employees WHERE id = ?"); //LIMIT 1
$stmt->bind_param('i', $del_id);
$confirmDelete = $stmt->execute();

$array['success'] = FALSE; //Initialize the success parameter as false.
if($confirmDelete){ //Check to see if there was an affected row.
  $array['success'] = TRUE;
}

echo json_encode($array);
?>

Partial Solution: Sample format how to setup the ajax. You have to start off by using the datatables.net "ajax": method for the original server.php. But then after that you use the normal $.ajax methods for the add.php, delete.php, etc. It is confusing because you use two different syntax for ajax. Easiest to just look at the sample link. Youtube video for same code

Another helpful link that discusses sending info to and from the ajax/json are one two three Four

3
  • You need to send data to server with ajax to let it know to remove from database. Server has no idea you remove something from inside the browser only. Studying some ajax tutorials should help Commented Aug 20, 2018 at 2:54
  • Ok. I will. While you are online... I am assuming the end result will look something along the lines like this? $.ajax({ url: 'remove.php', type: 'POST', data: { id:deleteid }, success: function(response){ // Removing row from HTML Table $(el).closest('tr').css('background','tomato'); $(el).closest('tr').fadeOut(800, function(){ $(this).remove(); }); } }); Commented Aug 20, 2018 at 2:57
  • yes except you are showing using $_GET['del'] which doesn't match your method or object key for the data Commented Aug 20, 2018 at 3:01

2 Answers 2

1

Updated answer using your latest updated code.

JS

$(function(){
    $(document).on('click','.delete_btn',function(){

        var del_id= $(this).closest('tr');
        var ele = $(this).parent().parent();  //removed the "$" from the ele variable. It's a js variable.
        console.log(del_id);

        $.ajax({
            type:'POST',
            url:'delete.php',
            dataType: 'json', //This says I'm expecting a response that is json encoded.
            data: {  //Set up your post data as an array of key value pairs.

              'del_id' : del_id

            }, 

            success: function(data){ //data is an json encoded array.

              console.log('Data: ' + data); //Going to display whats in data so you can see whats going on.

              if(data['success']){  //You are checking for true/false not yes or no.
                console.log('You successfully deleted the row.');
                ele.fadeOut().remove();
              }else{
                console.log('The row was not deleted.');
                }

             }

            });
        });
});

delete.php

$del_id = $_POST['del_id']; 
$stmt = $con->prepare("DELETE FROM employees WHERE id = ?"); //LIMIT 1
$stmt->bind_param('i', $del_id);
$confirmDelete = $stmt->execute();

$array['success'] = FALSE; //Initialize the success parameter as false.
if($confirmDelete){ //Check to see if there was an affected row.
  $array['success'] = TRUE;
}

echo json_encode($array); //Your ajax is setup to expect a json response.  
//json_encode the $array and echo it out.  You have to do this.  
//When you "echo" out a value, that is what the server is going to submit back to the ajax function.
//If you do not do this, the ajax script will not recieve a response from the delete.php page.

This code should work for you.

Sign up to request clarification or add additional context in comments.

21 Comments

Thank you for info. Will carefully read your post and this youtube video. And will try out your code. May have a question in a day or so. Thanks.
Hey no problem.. There is a ton of info out there on jquery/ajax. I find it is best just to get a simple ajax request to work, then add the stuff you need it to later. Anyways Cheers!
silly question... here is my ajax code (that currently works). var table = $('#example').DataTable( { "processing": true, "serverSide": true, "ajax": { "url": "server.php", "type": "POST", }, What is the difference between "ajax": versus $.ajax({
This ajax format uses "ajax": datatables.net/examples/data_sources/ajax.html not $.ajax({
The difference is that you are using some sort of class named dataTable. The dataTable has an ajax "method" built into it. You are telling the dataTable class to "use" ajax. And in the ajax method you supplied a url and the type. $.ajax would be if you were to write your own ajax properties for your own custom function outside of the dataTable class. Does that help?
|
0

In addition to Joesph's response who was extremely helpful:

"The console shows "Uncaught RangeError: Maximum call stack size exceeded". It looks as though the Ajax call isn't being issued (nothing is showing on the network tab) - so it must be when creating the request. I suspect I may need to JSON.stringify your del_id."

Someone suggested this: "The main stack problem is caused by var edit_id = $(this).closest('tr'); . You try to send that whole jQuery object as data in the ajax. Then jQuery can't serialize it internally and throws a fit

You probably want some property like ID or a data attribute from that row to send (not clear what expectations are)."

Please post if you have any recommendations. I will edit in any finalized code solution soon.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.