Display Alert Box Upon Form Submission
Solution 1:
First, a couple points:
Variables (even globals) are not shared across requests like you're trying to do in your bottom example. In order for
$postedto be accessible in both pages, you must persist it in some way. Usually this involves setting a session variable (e.g.$_SESSION['posted'] = true;), but it could also be persisted in a cookie, in a database, on the filesystem, in a cache, etc.Use something like
if ($_SERVER['REQUEST_METHOD'] === 'POST')instead ofif ($_POST). While the latter is probably safe in most cases, it's better to get in the habit of using the former because there exists an edge case where$_POSTcan be empty with a validPOSTrequest, and it may be a hard bug to track down.
One potential pattern to solve your problem using the above advice:
pageOne.php:
<?php
session_start();
if (isset($_SESSION['posted']) && $_SESSION['posted']) {
unset($_SESSION['posted']);
// the form was posted - do something here
}
?>
...
<form>...</form>pageTwo.php:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_SESSION['posted'] = true;
// do form processing stuff here
header('Location: pageOne.php');
exit;
}
// show an error page here (users shouldn't ever see it, unless they're snooping around)Solution 2:
It looks like it's a scope problem. use:
global$posted = true;
Post a Comment for "Display Alert Box Upon Form Submission"