derf
derf

Reputation: 1

How to Redirect to another php file using javascript

Okay, so here's my code

<?php
$cn = new mysqli ("localhost", "root", "root", "dbsam");
$username = isset ($_POST['username']) ? $_POST['username']:"";
$password = isset ($_POST['password']) ? $_POST['password']:"";
$sql = "SELECT * FROM tbluser WHERE username=? AND password=?";
$upass = hash("SHA256", $password);
$qry = $cn->prepare($sql);
$qry->bind_param("ss", $username, $upass);
$qry->execute();
$qry->fetch();
if ($qry->num_rows()==1) {
    echo "Logged in!";
}
else {
    echo "<script>alert('Account did not match the database records!')</script>>";
    header ("location: login.php");
}
?>

If the username and password did not match, an alert box will appear. So the problem is that it doesn't appear anymore it only executes the header that I put under it but if I remove the header, the alert dialog box will appear. I want the alert box to appear then the user will be redirected to the log-in page after that. How can I do that? Great Thanks!

Upvotes: 0

Views: 1010

Answers (2)

Seif.ben
Seif.ben

Reputation: 62

It is impossible in such way, PHP will redirect and never let the browwer executing the JS.

You can add a variable in the url then make your test in login.php then show the alert

    .....
    else {
        header ("location: login.php?mode=login_failed");
    }

    //login.php
    $mode = filter_input(INPUT_GET, 'mode');
    if ($mode === 'login_failed') {
         echo '<script>.......';
    }

Upvotes: 1

Carlo
Carlo

Reputation: 2112

You can set document.location, inside a script tag. Something like

<script> document.location = 'login.php'; </script>

Beside the answer to the direct question, I feel like you will need a timeout, or something more complex to handle the time spent reading the alert.

Upvotes: 2

Related Questions