Delete a HTMLtable row using AJAX

  • Frameworks used: JavaScript, AJAX, HTML. Cannot use JQuery

  • Have to display SQL table on page

  • Last column of the table should contain an image which acts like a delete button

  • On clicking that delete image, the row should be deleted from HTML table and SQL table

  • In my code the onClick is not working and I’m really struggling with it. Please help.

HTML code

table rows displayed by looping through rows of sql query result.

<td>
  <span class="delete" onClick="divFunction()" data-id="<?= $id; ?>"
    ><img src="delete.png"
  /></span>
</td>

JavaScript code

document.addEventListener("DOMContentLoaded", function () {
  function divFunction() {
    // Storing element that will be deleted
    var el = document.getElementById("delete");
    var deleteid = el.getAttribute("data-id");

    // Creating AJAX request
    var params = "id=" + deleteid;
    var request = new XMLHttpRequest();
    request.open("POST", "remove.php", true);
    request.setRequestHeader(
      "Content-type",
      "application/x-www-form-urlencoded"
    );
    request.send(params);
    el.remove();
  }
});

PHP Code

file name: remove.php

if (($con = mysqli_connect("localhost", "user", "password", "database", "port"))==false) {
  die(mysqli_connect_error());
}

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

// Delete the row
$query = "DELETE FROM Coorporations WHERE id='".$id."'";
mysqli_query($con,$query);
mysqli_free_result($result);
mysqli_close($conn);
exit;

Answer

Seems like you might have made things a bit too complicated. Let’s assume you’ve the following table:

<table>
    <tr>
        <td>
            <!-- 
               Let's not define any onclick handlers here, 
               we'll do that in an instant. 

               For demonstration purposes, let's give all elements 
               a hardcoded id.
            -->
            <span class='delete' data-id='1'>Delete entry</span>
        </td>
    </tr>
    <tr>
        <td>
            <span class='delete' data-id='2'>Delete entry</span>
        </td>
    </tr>
</table>

Inside a <script> tag at the bottom of your HTML document, or in a separate file, you might want to try:

// Grab all elements taht should fire an event when clicked  
let elements = document.querySelectorAll('span.delete');

for (let i = 0; i < elements.length; i++) {

    // Attach an event listener to them    
    elements[i].addEventListener('click', function(e) {

        // 'e' is the event object itself, 'target' the one
        // that triggered the event in the first place, i.e.
        // one of those <span> elements.
        let element = e.target
        let id      = e.target.dataset.id;

        console.log(id);

        // AJAX stuff
        // ...
    });

}

See also: