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

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;
halfer
  • 19,824
  • 17
  • 99
  • 186
Tan
  • 3
  • 4
  • 2
    Just a heads up, your code is *wide* open to a critical SQL injection vulnerability. – esqew Apr 06 '21 at 20:48
  • 3
    "*Cannot use JQuery*" - then why tag the question with [jquery]? – freedomn-m Apr 06 '21 at 20:50
  • `onClick="divFunction(this)"` and `function divFunction(el) {` then remove the `var el=` – freedomn-m Apr 06 '21 at 20:51
  • @esqew thanks for letting me know about that. I'm planning to shift focus to security once I get the functionality right cause i'm worried of making other errors there. – Tan Apr 06 '21 at 20:55
  • Using `document.getElementById('delete')` won't work with your HTML either. The "delete" key is used as a class, not an id. You could try to use something like `document.querySelector('.delete')`, but presumably there will be many rows that have that same class. Using @freedomn-m 's suggestion should help fix that problem. – legacybass Apr 06 '21 at 21:03
  • 2
    You'll have another problem with the `divFunction` method not being visible to the HTML. You're using the `DOMContentLoaded` event to only do things when the DOM is loaded, but you've declared the `divFunction` within the callback of that event registration. Basically, `divFunction` isn't visible outside that callback, and so won't be visible to the `onClick` event in your HTML. – legacybass Apr 06 '21 at 21:05
  • @freedomn-m thanks for the help. i tried that but the onClick still isn't working. Could it be that there's an error with the JavaScript that's preventing it from working? – Tan Apr 06 '21 at 21:07
  • `consolo.log(params);` what value do you get? use `var params = deleteid;` and in your php page `$_POST['deleteid']`. –  Apr 06 '21 at 21:14
  • @legacybass thank you. How can I make the `divFunction` visible to `onClick`? – Tan Apr 06 '21 at 21:19
  • thanks for that spot @Dean I can't get the value of `console.log(params);` as onClick has to work for that first :( I will try to fix that and then implement it – Tan Apr 06 '21 at 21:28
  • Just move it out of the DOMContentLoaded callback. It's just a function, so it doesn't need to wait for anything. Whatever is invoking it might, but the function itself doesn't. – legacybass Apr 07 '21 at 22:58

2 Answers2

1

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:

nosurs
  • 680
  • 6
  • 13
0

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();
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Daniel
  • 34,125
  • 17
  • 102
  • 150