1

I want to delete a row in my database according to the ID that the row is. Each row has a delete button and that button is placed by using a form in the php file for each row. I used an javascript function with ajax to display the table I wanted but now I have another function that I want to use to delete a row according to it's ID.

The problem I encountered was that every time I click the delete button my whole page just refreshes and the record is still there. Any help?

P.S. I'm new to php, ajax, and especially javascript and have not learned any jQuery so preferably help would be appreciated if codes were to be written in pure javascript as I want to learn the basics first.

This is the function in the javascript to delete the row using ajax xmlhttp object.

function deleteThis(){
 var del = document.getElementById("delete");
 var delRow = document.getElementById("deleteRow");
 var page = "database.php";
 var parameters = 'delete='+del+'&deleteRow='+delRow;
 var xmlhttp = new XMLHttpRequest();
 if(confirm('Are you sure you want to delete this?')==true){
 xmlhttp.onreadystatechange=function(){
 if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
  //What should be in here?
  }
 }
  xmlhttp.open("POST", page, true);
  xmlhttp.send(parameters);
 }
}

These are the codes in the php file to delete the row

// Delete Row
if(isset($_POST['delete'])){//java script function somewhere
 $id = $_POST['deleteRow'];
 $query_string = "delete from $table_info where user_id='$id'";
 $result = @mysql_query($query_string);
 echo "row deleted";
}else {
 echo "Cannot delete row";
}

This is the button inside a table to put a delete button for each row.

<!--Delete button-->
<td><form id="delete" method="post" action="">
<input type="hidden" name="deleteRow"  value="<?php echo $row['user_id']; ?>"/>
<input type="submit" name="delete" value="Delete" id="delete" onclick="return deleteThis()"<td></form></tr>
pizzaisdavid
  • 455
  • 3
  • 13
kross
  • 475
  • 1
  • 11
  • 31

2 Answers2

1

First, you have multiple issues with your HTML. I would suggest you indent your code consistently to help point out issues. Also, remember to close your tags. For example:

<td>
    <form id="delete" method="post" action="">
        <input type="hidden" name="deleteRow"  value="<?php echo $row['user_id']; ?>"/>
        <input type="submit" name="delete" value="Delete" id="delete" onclick="return deleteThis()">
    </form>
</td>

Also, if you this button next to every row on the page you shouldn't give it an id. ids need to be unique on a page (only one of each). Perhaps you should use a class instead?

Second: a submit type of input will literally submit its enclosing form and refresh the page. Thats its purpose. If you want to use AJAX, you don't want to actually do this.

What I would suggest is putting another function into your javascript and referencing this from the onclick of a <button> rather than an <input>. Then you can properly prevent submission of the page.

Eg:

<td>
    <form id="delete" method="post" action="">
        <input type="hidden" name="deleteRow"  value="<?php echo $row['user_id']; ?>"/>
        <button name="delete" class="delete" onclick="javascript:handleDeleteClick(event, <?php echo $row['user_id']; ?>);">Delete</button>
    </form>
</td>

And in your javascript:

function handleDeleteClick(e, userId) {
    e.preventDefault(); // Prevent default behaviour of this event (eg: submitting the form

    // Perform the AJAX request to delete this user
    var delRow = document.getElementById("deleteRow");
    var page = "database.php";
    var parameters = 'delete=true&deleteRow='+delRow;
    var xmlhttp = new XMLHttpRequest();

    if (confirm('Are you sure you want to delete this?') == true) {
        xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                // Request completed
            }
        }

        xmlhttp.open("POST", page, true);
        xmlhttp.send(parameters);
    }
}
Alex McMillan
  • 17,096
  • 12
  • 55
  • 88
  • I see, that would explain why it refreshes every time. I've tested it out and it doesn't refresh anymore however, to execute my query I required ` if(isset($_POST['delete']))` so now if I don't have an ID for it how do I get the button? Or rather how do I know if it's clicked so that in my PHP file I can execute my query? – kross May 11 '15 at 03:22
  • An ID for the delete button* – kross May 11 '15 at 03:31
  • Why do you want to send the element as a POST parameter? You could just send "delete=true" like my example, no? Is `` the unique ID you need to determine which user to delete? If so, then that's sent as `deleteRow` in the POST parameters. – Alex McMillan May 11 '15 at 03:44
  • The unique ID is what I need to determine which user to delete. I was referring to my PHP file for the first `IF` statement as that was what I used to determine if the button is clicked now. As you have suggested to change the submit type to a button type for the delete button, now how do I determine if the button is clicked for the if statement? Do pardon me if the answer seems obvious because I'm still new to the PHP language and concept of it. – kross May 11 '15 at 03:54
  • Don't worry - we love newcomers! Programming is fun! In your PHP: `if(isset($_POST['delete'])){` you are checking the $_POST object to see if it contains a variable called `delete`. In the javascript example I gave, have a look at the line `var parameters = 'delete=true&deleteRow='+delRow;`. See the `delete=true` ? This is setting the variable to `true`, so it should still work. Is it not working? – Alex McMillan May 11 '15 at 03:59
  • Yeah it doesn't remove the row in the database. I have limited means of debugging as I am using vi editor to edit the file on a server so I'm using IE's web developer tool to debug. It seems after it completes `if(xmlhttp.readyState == 4 && xmlhttp.status == 200)` 3 times, the program ends. – kross May 11 '15 at 04:06
  • Perhaps you could add a `console.log(xmlhttp.readyState, xmlhttp.status);` inside that function and see what status the server is returning? This is the beginning of debugging and I'm afraid I can't be much help after this :( – Alex McMillan May 11 '15 at 04:18
  • Ahh I see. Alright, thanks for the help anyway. @Jonathan-Prates too. – kross May 11 '15 at 05:06
0

Try this:

<input type="submit" name="delete" value="Delete" id="delete" onclick="return deleteThis(); return false"><td></form></tr>

It will avoid to submit form. Take a look: event.preventDefault() vs. return false

Here is a snippet for you:

<script>
  function deleteThis() {
    "use strict";
    var sure = confirm('Are you sure you want to delete this?');
    if (!sure) {
      return;
    }

    var del = document.getElementById("delete");
    var delRow = document.getElementById("deleteRow");
    var page = "database.php";
    var parameters = 'delete=' + del + '&deleteRow=' + delRow;
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function(data) {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        alert("Form sent successfully");
      }
    }
    xmlhttp.open("POST", page, true);
    xmlhttp.send(parameters);
  }
</script>

<form id="delete" method="post" action="?">

  <input type="hidden" name="deleteRow" value="<?php echo $row['user_id']; ?>" />
  <input type="submit" name="delete" value="Delete" id="delete" onclick="deleteThis(); return false;">

</form>
Community
  • 1
  • 1
Jonathan Simon Prates
  • 1,122
  • 2
  • 12
  • 28
  • Thank you @jonathanprates for that however, what should I put in after this if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ – kross May 11 '15 at 02:28
  • onclick="return deleteThis(); return false" <--- I think you need to put return false in HTML to avoid page refresh. – Jonathan Simon Prates May 11 '15 at 02:30
  • Your `return deleteThis()` will cause your `return false;` to never be executed, as the event will have already returned. Perhaps you mean: `onclick="deleteThis(); return false;"` ? Anyway, there are [many reasons](http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/) not to do this. – Alex McMillan May 11 '15 at 02:42
  • Thank you @alex-mcmillan. I forgot to remove the first return. – Jonathan Simon Prates May 11 '15 at 02:58