0

After running a POST script I want to navigate back to the page that called it. At the end of the script I can call something like this to navigate back:

header("Location: /url/to/the/other/page");

But the restriction using that is that I cannot output to the user "successfully inserted data to database" before that call. On coming back to the original page, how can I display that notification?

3
  • Can you use javascript to POST to the script that handles the db instead? Commented Oct 13, 2017 at 22:08
  • you can pass a parameter to it Commented Oct 13, 2017 at 22:09
  • Set a variable in $SESSION before redirection. Then access this at the new location Commented Oct 13, 2017 at 22:09

1 Answer 1

1

Strictly speaking, you can't redirect from a page with headers that also show output. You can either send output to the browser, or you can send a redirect header, but not both.

If you want to display something, wait a few seconds, and then send a redirect, you'll want to use a client-side redirect in JavaScript. Something like this:

<html>
    <head>
        <script type="text/javascript">
            setTimeout( function() {
                location.href='/newpage.html',
            }, 5000 );
        </script>
    <body>
        successfully inserted data to database.
    </body>
</html>

This will render what's in <body>, wait 5 seconds, then execute the function in setTimeout() which redirects the page.

Technically, that's not true.. the 5 second counter begins as soon as the JS executes whether or not the page is done loading.

If you're wanting to display the notification on the same page that you called from rather than redirecting to an intermediary page, then you should set a session value:

$_SESSION['note'] = 'data_saved';

Then on the page where you want to display the notification:

if ( isset( $_SESSION['note'] ) && $_SESSION['note'] == 'data_saved' ) {
    echo "successfully inserted data to database.\n";
    unset( $_SESSION['note'] );
}

This will require that you run session_start() at the top of any page that references $_SESSION;

Sign up to request clarification or add additional context in comments.

1 Comment

The above example of using $_SESSION worked perfectly for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.