Tan
Tan

Reputation: 3

Delete a HTMLtable row using AJAX

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;

Upvotes: 0

Views: 277

Answers (2)

Daniel
Daniel

Reputation: 35684

I'll try and take a guess. You are missing the delete id from the element, but you shouldn't be using the id, since that would only return the first element matching. (html standard defines the id as being unique)

Instead of var el = document.getElementById("delete"); you may want to try using the passed target.

Also, as pointed out by @legacybass, you shouldn't define the function in the DOMContentLoaded listener-triggered method because it will not get hoisted.

function divFunction(event) {
  // Storing element that will be deleted
  var el = event.target;
  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();
}

in fact, you may even be able to just pass the id, if it is being rendered by the server.

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

JavaScript code

function divFunction(deleteid) {
  // 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();
}

Upvotes: 0

nosurs
nosurs

Reputation: 665

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:

Upvotes: 1

Related Questions