Search code examples
javascriptphpconfirm

Javascript confirm() still executes action when cancel is clicked. :(


<script type="text/javascript">
confirm("Delete user?.");
window.location.href = "users.php";
</script>
$qqq = mysql_query("DELETE from users WHERE panelistname='$theuser'") or die(mysql_error())

considering the code above, (inside a php file, so no worries with certain syntax errors you might notice) the problem here is that when click cancel on the confirm() dialog box that will show up. the delete action still executes. This question might be considered a double since, yeah, I found some questions relevant to this one but I just can't fixed this one myself. the one I found codes it something like this:

"if (confirm('Are you...?')) commentDelete(1); return false"

I can't find a way to solve this problem, I don't know which part should I insert the SQL command(delete) in this format. Please someone show me how to do this right. :) thanks!


Solution

  • EDIT: I just saw that Nick Zuber posted a similar answer around 1 minute before I posted mine (actually, while I was writing it :P)

    I don't clearly understand what you are trying to do. You want to show the user a confirm window, and if they click Yes, delete some entry in the database, and if they click No, redirect them to the page 'users.php' ?

    If it's what you want to do, then you can't do it like this. You can't use JS conditions with PHP. The PHP code is executed server-side (in the server), whereas the JS code is executed client-side (in the browser). What you would need is to do something like this:

    warning: don't use this code, it's unsecure and shouldn't ever be used in a real app, it's just to show you how the whole thing works

    (IN USERS.PHP)

    if(isset($_GET['delete_dat_user']))
    {
        $qqq = mysql_query("DELETE from users WHERE panelistname='" . $_GET['delete_dat_user'] . "'") or die(mysql_error());
    }
    

    (IN THE WEBPAGE)

    if(confirm('u serious u want to delete the user'))
    {
        window.location = 'users.php?delete_dat_user=theUserName';
    }
    else
    {
        nope
    }