I have a page where users submit a form, and it goes to a separate PHP script. After the script is done, it header() redirects the user back to the page they were on. Now what I want to do is if there is an error or certain conditions in the script, redirect the user to the same page but display a Javascript alert once they get there as a warning message. I could append some variables to the URL and check for that with $_GET but I figure there is probably an easier way... perhaps with some POST data, or something like that? Thanks
You can do this all on the server side by using the session:
"Show form" php script creates the form and returns it to the user.
User fills it out and submits it to another php script "receive script" which receives the form data, and notices an error, missing data, etc.
The "receive script" stores the error msg in the session (as item err) and redirects to the 'show form' script.
The "show form" script (same as in step 1) actually does more than create the form. It also:
- looks in the session to see if it has an item 'err', an error msg. In step 1 there wasn't. But now there is. So the php script creates the form, along with a div that shows the error msg to the user.
- Resets the session's 'err' item to nil.
- The php script could also include javascript in the page which would make the error msg disappear after a while or be shown as a popup, etc.
ps. The above flow is how rails handles forms and redisplay of the form.
Update: Thanks to @zod for pointing out that I wasn't clearing the err item in the session.
If an error is encountered, store the error state to a $_SESSION array and then redirect the browser to the original page. Have a script on the original page to check if an error state is set. If yes, trigger a javascript alert or whatever handling you want to have.
And at the common footer template (or at the footer of original page), check and clear the errors array, so it doesn't persist when the user moves to other pages or reloads the current page.
Example:
processor.php
<?php
if($something == $iswrong){
$_SESSION['errors']['error5301'] = 1;
session_write_close();
header("Location: http://www.example.com/originalpage.php");
exit;
} ?>
originalpage.php
<!-- Header -->
<?php
if(isset($_SESSION['errors']['error5301']) && $_SESSION['errors']['error5301'] == 1){ ?>
<script type="text/javascript">
alert('Something is not correct!');
</script>
<?php } ?>
<!-- Some page content -->
....
.....
..
......
<!-- Footer -->
<?php
if(isset($_SESSION['errors'])){
unset($_SESSION['errors']);
} ?>
Hope that helps.
first page
<script>
onsubmitfunction()
{
document.getElementByid('errorid').value=1;
}
</script>
<form name='' id='' onsubmit="javascript:onsubmitfunction();">
<input type='hidden' id='errorid' value=''>
</form>
In destination.php
<?php
if($_POST['error']==1)
{
?>
<script language='javascript'>
alert('Errrrrorrrr');
</script>
<?
}
?>
This is enough for your question.
As per my understanding