So I have these two pages: pageOne.php
and pageTwo.php
.The form is in pageOne.php
:
<form method="post" action="pageTwo.php"> .... </form>
and doing all the data collection-validation-insertion and sending out mails in pageTwo.php
(the reason i'm doing everything in two separate pages is to avoid the data re-submission upon page refresh...this was the easiest way for me to handle the issue). So far everything is working perfectly.
Now, I want to display a success/failure message using alert box after the form submission and tried few things w/o any luck. E.g. when I tried THIS solution on pageTwo.php
, no pop up box shows up and I think that's because I have this header
on top of that page
<?php header("Location: http://TestPages.com/pageOne.php"); ?>
<?php
if( $_POST ) {
//collect the data
//insert the data into DB
//send out the mails IFF the data insertion works
echo "<script type='text/javascript'>alert('It worked!')</script>";
}else
echo "<script type='text/javascript'>alert('Did NOT work')</script>";
?>
And when tried this second solution in pageOne.php
, I get the alert box popping up every time i refresh the page and get the failure message even though the data had been inserted into database and mails were sent out. pageOne.php
:
<html>
<body>
<?php
if( $GLOBALS["posted"]) //if($posted)
echo "<script type='text/javascript'>alert('It worked!')</script>";
else
echo "<script type='text/javascript'>alert('Did NOT work')</script>";
?>
<form method="post" action="pageTwo.php"> .... </form>
</body>
and in pageTwo.php
:
<?php header("Location: http://TestPages.com/pageOne.php"); ?>
<?php
$posted = false;
if( $_POST ) {
$posted = true;
//collect the data
//insert the data into DB
//send out the mails IFF the data insertion works
} ?>
Why isn't this simple thing working :( ? is there any easy way to fix it? Thank you!!
UPDATE
So I have made some changes according to drrcknlsn's sugession and this is what I have so far....pageOne.php
:
<?php
session_start();
if (isset($_SESSION['posted']) && $_SESSION['posted']) {
unset($_SESSION['posted']);
// the form was posted - do something here
echo "<script type='text/javascript'>alert('It worked!')</script>";
} else
echo "<script type='text/javascript'>alert('Did NOT work')</script>";
?>
<html> <body>
<form method="post" action="pageTwo.php"> .... </form>
</body> </html>
and pageTwo.php
:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_SESSION['posted'] = true;
//collect the data
//insert the data into DB
//send out the mails IFF the data insertion works
header('Location: http://TestPages.com/pageOne.php');
exit;
} ?>
With these changes now the page's redirection and success message is working, but i get the failure msg every time i open/refresh the page (i know that's because the session key is not set yet)...how can i avoid that? Thanks again!!