Search code examples
phpjavascriptconfirmation

How to popup a JavaScript confirmation window before executing PHP?


How to popup a JavaScript confirmation window before executing:

<form action="index.php" method="get">
  <input type="hidden" name="act" value="run">
  <input type="submit" value="Clear map">
</form>
<?php
  if (!empty($_GET['act'])) {
        mysql_query("TRUNCATE TABLE mapinfo");
        $page = $_SERVER['PHP_SELF'];
        header("Location: $page");
  } 
?>

User has to press OK to execute PHP or Cancel to not.


Solution

  • <?php
      // mysql connection
      if ($_GET['act'] == 'run') {
            mysql_query("TRUNCATE TABLE mapinfo");
            $page = $_SERVER['PHP_SELF'];
            header("Location: $page"); // for this to work, script must not output something before, otherwise use echo '<script type="text/javascript">window.location = \''.$page.'\';</script>';
            die;
      } 
    ?>
    <form action="index.php" method="get" onsubmit="return confirm('Are you sure you want to truncate `mapinfo`?');">
      <input type="hidden" name="act" value="run">
      <input type="submit" value="Clear map">
    </form>