Skip to content Skip to sidebar Skip to footer

Server-side Table Deletes Row From Tables (but Not Database) Using JS, Php, Or Ajax

Project Link: https://databasetable-net.000webhostapp.com/ This following code correctly deletes a row in a table: $('#example').on('click', '.delete_btn', function () {

Solution 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.


Post a Comment for "Server-side Table Deletes Row From Tables (but Not Database) Using JS, Php, Or Ajax"