简体   繁体   中英

PHP/HTML navigate to another page AND display output?

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?

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 ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM