0

I created a user interface to allow people to do simple CRUD operations, I'm using AJAX PHP and JQUERY for that matter. I'm able to delete rows on page load for the first time. But after I hit the reload button which reloads the div which contains the table, I am not able to delete yet another item.

My question is, how could I do this?

index.php


  <div id="table-reload" class="container-fluid">
      <?php

        include("dbServer.php");


        $sql = "SELECT * FROM product";

        $result = $db->query($sql);

        if ($mysqli->connect_errno) {
          printf("Connect failed: %s\n", $mysqli->connect_error);
          exit();
        }
        // Printing all DataBase Items
        echo "<table><tr><th>ID</th><th>Name</th></tr>";

        while ($row = $result->fetch_object()) {

          $id = $row->id;
          $name = $row->name;
          $description = $row->description;
          $price = $row->price;
          $picture = $row->picture;

          echo "<tr><td>".$id."</td><td>".$name."</td><td>".$description."</td><td>".$price."</td><td>".$picture."</td><td><button data-id='".$id."' class='delete btn btn-light'>DELETE</button></td><td><button class='update btn btn-light'>UPDATE</button></td>";
        }

        echo "</table>";



      ?>

    </div>

    <!-- Reload Button -->

    <button id="reloader" class="container-fluid btn btn-primary" type="button" name="button">Reload</button>

index.js

  $("#reloader").click(function(){
    $("#table-reload").load(" #table-reload");
  });

  $(".delete").click(function(){

    var obj = $(this);
    console.log($(this));
    var deleteId = $(this).data('id');
    console.log(deleteId);

    $.ajax({
      url: "delete.php",
      method: "POST",
      data: {id: deleteId},
      success: function(){
        $(obj).closest('tr').fadeOut(1000, function(){
          $(this).remove();
        });
      }
    });
    return false;

  });

delete.php

<?php include ("dbServer.php");

  $id = 0;
  if (isset($_POST['id'])){
    $id = mysqli_real_escape_string($db, $_POST['id']);
  }

  if ($id > 0) {
    //Checking if item with id exists in db
$checkRecord = mysqli_query($db, "SELECT * FROM product WHERE id=".$id);
    $totalRows = mysqli_num_rows($checkRecord);

    if ($totalRows > 0){
      //Delete record
      $query = "DELETE FROM product WHERE id=".$id;

      if ($db->query($query) === TRUE){
        echo "data deleted";
      }
      else {
        echo "failed to delete";
      }
    }
  }


?>

0 Answers0