Delete Task on a todo list, without refreshing the site with PHP

Viewed 14

I am working an a to-do list with php and mysql. I have already connected my programm with the Database. Now I have this output:

2022-09-24 X Task1
2022-09-24 X Task2
2022-09-24 X Task1

the HTML looks

<ul>
  <li><span>X  </span>Task1</li>
  <li><span>X  </span>Task2</li>
  <li><span>X  </span>Task3</li>
</ul> 

How i can delete a Task with php, if I click on "X" without refreshing the site?

1 Answers

your HTML should like (don't forget to save the file as PHP):

  <tr class="delete_task<?php echo $id ?>">
     <td><?php echo $row_task['task_name']; ?></td>

     <td>
        <a class="btn btn-success" id="<?php echo $id; ?>">Delete</a>
     </td>
  </tr>

you need to add event on button with js code first

<script type="text/javascript">
    $(document).ready(function() {
        $('.btn-success').click(function() {
            var id = $(this).attr("id");
            if (confirm("Are you sure you want to delete this Member?")) {
                $.ajax({
                    type: "POST",
                    url: "task_delete.php",
                    data: ({
                        id: id
                    }),
                    cache: false,
                    success: function(html) {
                        $(".delete_task" + id).fadeOut('slow');
                    }
                });
            } else {
                return false;
            }
        });
    });
</script>

your PHP code in task_delete.php

<?php
include ('database.php'); // your DB connection
$id = $_GET['id'];
$delete_data"delete from tasks where task_id = '$id' ";
$database->exec($delete_data);
?>
Related