最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to popup a JavaScript confirmation window before executing PHP? - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Sep 12, 2012 at 12:48 Szymon TodaSzymon Toda 4,52612 gold badges44 silver badges62 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8
<?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>

Use javascript confirm() to do so. Add an onclick attribute to the submit button that will call a confirm dialog and check with javascript if option yes then some code and if not then some other code.

PHP script is evaluated on the server, before the site is sent to the client. The javascript is evaluated only when the client starts processing the page. So you cant really do anything in javascript before the php script is evaluated.

A solution would be to set up a proxy page that handle the javascript stuff you need, and then refer you to the php page.

Hope that helps!

Try this one line,

<a href="truncate_page.php" onclick="return confirm('Are you sure you want to truncate?')">Truncate</a> 
发布评论

评论列表(0)

  1. 暂无评论