简体   繁体   中英

How to make a button that is directing you to another page, in php/Jquery(javascript)?

Hello I'm making a very basic "Login system" without sql database yet.

I want when I press "Start Session" it will start the session (log-in) and it'll redirect me to my second page(Home page) where a button "Destroy Session" (log-out) will apear, which will redirect back to the first page where you can log-in.

page1.php code (log in):

<html>
<head>

    <script src="http://code.jquery.com/jquery-latest.min.js"></script>

    <script>
        $(document).ready(function()
        {
        // For starting the session
            $('#start_session').click(function()
            {
                header("location:page2.php");
                $('#message').load('start_session.php')


            });
        });
    </script>

</head>

<body>
    <div id='message'></div>
    <input type="button" value="Start Session" id="start_session">
</body>

page2.php code (log out):

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>

    <script>
        $(document).ready(function()
        {

        $('#destroy_session').click(function()
            {
                header("location:page1.php");
                $('#message').load('destroy_session.php')

            });
        });
    </script>

</head>

<body>
    <div id='message'></div>

    <input type="button" value="Destroy Session" id="destroy_session">
</body>

start_session.php code:

    <?php



session_start();



if(!isset($_SESSION['visits']))
{
    $_SESSION['visits'] = 0;
}

else
{
    $visits = $_SESSION['visits']++;

    if ($visits == 0)
    {
        echo "This is your first time on this site, isn'/t it? <br />";
    }

    else 
    {
        echo "You have visited this site: $visits times.<br />";
    }


    exit();

    echo ' You are logged in';  
}

?>

destroy_session.php code:

    <?php
session_start();
echo $_SESSION['visits'];
unset($_SESSION['visits']);


echo "You have been logged out";
?>

Note: I have tried header('Location: page.php'); but this will redirect me instantly to page 2 from page 1 and I want it on the click.

In javascript your redirect using window.location.href :

$('#start_session').click(function() {
    $('#message').load('start_session.php', function() {
        window.location.href = 'page2.php';
    });
});

And you should redirect when you have processed your php so I put it in the callback function.

Note that you will not see the results that your php outputs because of the redirect so you should probably include that output in the next page.

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