How to show a success message after PHP form submission?
16,798
Solution 1
Where you have:
header('location:page1.php');
append a variable on the location, like:
header('location:page1.php?status=success');
And on page1.php, do something like:
if( $_GET['status'] == 'success'):
echo 'feedback message goes here';
endif;
Solution 2
This way your flash message will not show up again and again after refresh.
<?php session_start();
if(isset($_SESSION['msg']) && $_SESSION['msg'] != ''){
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
?>
<form action="page2.php" method="post"
enctype="multipart/form-data" class="form-inline subscribe-form">
<input type="name" name="name" placeholder="Jack">
</div>
<button type="submit" name="sub" value="sub" >Submit</button>
</form>
And
<?php
session_start();
//include necessary
if(isset($_POST['sub'])) {
$nameget = mysqli_real_escape_string($dbconnect, $_POST['name']);
$sqlentry = .....bla bla......//insert into DB
}
$getsql = mysqli_query($dbconnect, $);
if($getsql){
mysql_close($dbconnect);
$_SESSIOM['msg'] = 'Value Inserted or whatever';
header('location:page1.php');
}
?>
![sofa_maniac](https://i.stack.imgur.com/uAnVl.jpg?s=256&g=1)
Comments
-
sofa_maniac about 2 years
Here is the code. I want it this way --
Form submission --> page2.php --> redirect --> page1.php (Here is the message. Pop-up or whatever)
page1.php
<form action="page2.php" method="post" enctype="multipart/form-data" class="form-inline subscribe-form"> <input type="name" name="name" placeholder="Jack"> </div> <button type="submit" name="sub" value="sub" >Submit</button> </form>
page2.php
<?php //include necessary if(isset($_POST['sub'])) { $nameget = mysqli_real_escape_string($dbconnect, $_POST['name']); $sqlentry = .....bla bla......//insert into DB } $getsql = mysqli_query($dbconnect, $); if($getsql){ mysql_close($dbconnect); header('location:page1.php'); } ?>
-
sofa_maniac almost 9 yearsThis is fine. It worked, thanks. But when I refresh the "page1.php?status=success" page, is there any way to head to "page1.php"?
-
pbs almost 9 yearsSure, depends on what you want.. maybe store the status in a session, or maybe just do a simple redirect with javascript, or display the feedback in a alert or modal window, that links to page1.php..
-
Rimble almost 9 yearsDon't forget to unset the $_SESSION message else after page refresh it will still be there.
-
Rimble almost 9 yearsAlso add in a check for $_SESSION['msg'] on the top with an isset() statement else it will throw an error!
-
Tarun Upadhyay almost 9 yearsYes sure.. Added the same.
-
Rimble almost 9 yearsEdited your answer a little bit :)