how do i write a javascript alert box to give a yes or no question and integrate with php calls?

前端 未结 1 1876
予麋鹿
予麋鹿 2021-01-16 16:49

i am trying to figure out how to create a javascript alert box asking the user if they would like to delete a record (that their viewing) and when the user presses yes a que

相关标签:
1条回答
  • 2021-01-16 17:08
    if (window.confirm("Are you sure?")) {
      // call php code here, either through going to a new page,
      // or by doing an ajax request
    }
    

    For your update: The problem is that the PHP code is being executed by the server, which does not run the Javascript, and the Javascript runs at the client side, with no knowledge of the PHP code.

    This means the PHP code will always run, simply ignoring the the window.prompt call, as that is not part of PHP. The Javascript that is executed by the client looks simply like this:

    <script type="text/javascript">
    if(window.confirm("Are you sure you want to delete that record?")) { 
    }
    </script>
    

    Which obviously does nothing, if you were to even reach this page, because you are sending the user to a new page using the Location header.

    What you need to do is put the PHP code you wrote on a second page, and take the client to that page, only once the window.confirm() has run. Something like this:

    file1.php

    <script type="text/javascript">
    if(window.confirm("Are you sure you want to delete that record?")) {
      document.location = "file2.php?id=<?php echo $_GET['id'] ?>";
    }
    </script>
    

    file2.php

    <?php
    $id = $_GET['id'];
    if (!is_numeric($id)) $id = -1;
    mysql_query("delete from tbl_payments where id = '$id'") or die(mysql_error());
    header("Location: dashboard.php");
    ?>
    
    0 讨论(0)
提交回复
热议问题