Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript confirm on PHP delete button

How can I add a JavaScript alert to confirm (yes or no) when the user clicks the delete button? I tried adding a class to an alert:

<?php
//$con = mysqli_connect("localhost", "root", "root", "db");
$sql = "SELECT * FROM `uploads` where userId = " . $_SESSION['user'];
$qry = mysqli_query($conn,$sql) or die(mysqli_error($conn));

$table_content = "";

while($row = mysqli_fetch_assoc($qry)){
    $id = $row['id'];
    $name = $row['name'];
    $table_content .= "<tr>
                         <td>
                           <a href='listen.php?id=$id' target='_new'>$name </a>
                         </td>
                         <td>
                           <a href='delete.php?id=$id' type='button' class='btn btn-danger'>delete</a>
                         </td>
                       </tr>";
}

echo "<table>".$table_content."</table>";
?>
like image 325
Philly Hanna Avatar asked Jun 23 '26 08:06

Philly Hanna


2 Answers

For simplicity check this out.

<a onClick="return confirm('Are you sure you want to delete?')" href='delete.php?id=$id' type='button' class='btn btn-danger'>delete</a>

return false is actually doing three very separate things when you call it:

  • event.preventDefault();
  • event.stopPropagation();
  • Stops callback execution and returns immediately when called.

Since confirm method returns true or false, we can simply call it on onclick then the return determines the action.

reference: kamesh answer

 <a onClick="return confirm('Are you sure you want to delete?')" href='delete.php?id=$id' type='button' class='btn btn-danger'>delete</a>
       
like image 200
Lekens Avatar answered Jun 25 '26 21:06

Lekens


I think thats what you are looking for.

<a href='delete.php?id=$id' onclick="return myFunction()" type='button' class='btn btn-danger'>delete</a>

<script>
function myFunction() {
var r = confirm("OK to delete?");
if (r == false) {
   return false;
} 

}
</script>
like image 37
D. Pachauri Avatar answered Jun 25 '26 21:06

D. Pachauri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!