Delete a HTMLtable row using AJAX Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Delete a HTMLtable row using AJAX without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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

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

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();"POST", "remove.php", true);

PHP Code

file name: remove.php

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

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

// Delete the row
$query = "DELETE FROM Coorporations WHERE id='".$id."'";


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

               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>
            <span class='delete' data-id='2'>Delete entry</span>

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 =
        let id      =;


        // AJAX stuff
        // ...


See also:

We are here to answer your question about Delete a HTMLtable row using AJAX - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji