Skip to content

How to redirect to another page in HTML after login

To redirect to another page in HTML after login, you can use a combination of HTML and JavaScript. In this approach, a link with a redirect parameter in the URL is provided to the user to access the login page. After the user logs in, they will be redirected to the specified URL.

Redirect to another page in HTML after login example

A simple example code has a login form that submits to a PHP script called submit-login.php.

<!DOCTYPE html>
<html>
<head>
    <title>Login Page</title>
</head>
<body>
    <h1>Login</h1>
    <form action="submit-login.php" method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username"><br><br>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password"><br><br>
        <input type="submit" value="Login">
    </form>
    
    <script>
        // Get the URL parameter 'redirect'
        const urlParams = new URLSearchParams(window.location.search);
        const redirectUrl = urlParams.get('redirect');
        
        // If 'redirect' parameter is set, redirect to that URL after login
        if (redirectUrl) {
            // Wait until the page has fully loaded before redirecting
            window.onload = function() {
                window.location.href = redirectUrl;
            }
        }
    </script>
</body>
</html>

Output:

How to redirect to another page in HTML after login

To use this script, you can include a link to the login page with a redirect parameter in the URL, like this:

<a href="login.html?redirect=dashboard.html">Login</a>

To achieve this, you can create a login page with a login form that submits to a PHP script (or any other server-side script that handles the login logic). You can also include a JavaScript code that retrieves the value of a URL parameter called redirect using the URLSearchParams API. If the redirect parameter is set, the script waits until the page has fully loaded before redirecting the user to the specified URL.

Do comment if you have any doubts or suggestions on this HTML webpage topic.

Note: The All HTML Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *