Home > Software design >  Jsquery redirect after success login
Jsquery redirect after success login

Time:12-13

I'm trying to get a redirect to the home page after a successful login, but I don't know how. I've already used the sleep function but somehow it doesn't work. Can someone help me please ?

login.php `

<?php

include "message.php";

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
    if(($_POST["username"] == "admin" && $_POST["password"] == "admin"))
    {
        echo message::success("Your login was successfully.");
        sleep(5);
        header("Location: index.php");
    } else {
        echo message::error("Your entered details are wrong.");
    }

} else {
    header("HTTP/1.0 404 Not Found");
}

`

index.php `

<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>

<script>
    $(document).ready(function(){
        $("form").on("submit", function(event){
            event.preventDefault();

            var formValues= $(this).serialize();

            $.post("php/login.php", formValues, function(data){
                // Display the returned data in browser
                $("#msg").html(data);
            });
        });
    });
</script>

<body >
    <main >
        <div id="msg"></div>

        <form id="contactForm" method="POST" role="form">
            <h1 >Please sign in</h1>

            <div >
                <input type="username" name="username"  id="floatingInput" placeholder="Username">
                <label for="floatingInput">Username</label>
            </div>
            <div >
                <input type="password" name="password"  id="floatingPassword" placeholder="Password">
                <label for="floatingPassword">Password</label>
            </div>

            <div >
                <label>
                    <input type="checkbox" value="remember-me"> Remember me
                </label>
            </div>
            <input type="submit" name="login" >Sign in
            <p >&copy; 2022</p>
        </form>
    </main>
</body>

`

I've already used the sleep function but somehow it doesn't work

CodePudding user response:

You are using PHP redirect but AJAX requests don't follow response redirects by default. PHP header() will send redirect header, but it be captured by JS. This only works when you load login.php directly from browser.

You need to redirect user using Javascript:

$.post("php/login.php", formValues, function(data){
    document.location.href = 'index.php';
});

CodePudding user response:

you can try this

$.post("php/login.php", formValues, function(data) {
    // Display the returned data in browser
    $("#msg").html(data);
    if (data == `your success html`) {
      window.location = "index.php";
    }
});

change 'your success html' with your response ajax success

  • Related