-2

I am using ajax to post in the login part and create session. the session is working but in there header('location: chat.php') is not working(not redirected). while I am trying to log in session is created but not redirected to chat.php. I checked jQuery and ajax is working and successful to create a session and log in but not redirected to chat.php. Can any help me plz

jQuery('.userlogin').submit(function(){

            var email = jQuery("input[name='email_address']").val();
            var password = jQuery("input[name='password']").val();

            $.ajax({

                'url'   : 'login.php',
                'type'  : 'POST',
                'data'  : {
                    'loginajax' : '',
                    'email'     : email,
                    'password'  : password

                },
                'success'  : function(output){


                    jQuery('.ama-input').val('');
                }
            });



        });

<?php

session_start();

require_once('functions.php');


if(isset($_POST['loginajax'])){

    $email=$_POST['email'];
    $password=$_POST['password'];

    $query = mysqli_query($connection, "SELECT * FROM users WHERE email='$email'");

    $info = mysqli_fetch_assoc($query);

    $pass= $info['password'];

    if($pass==md5($password)){

        $_SESSION['login'] = "successful";

        header('location: chat.php');
    }




    die();
}



?>








<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Log In</title>

    <link rel="stylesheet" href="style.css">

</head>
<body>

    <div class="box">
        <h2 class="heading">Log In</h2>
        <form action="" method="POST" class="userlogin">

            <input class="ama-input" type="email" name="email_address" placeholder="Email Address" />
            <input class="ama-input" type="password" name="password" placeholder="Password" />

            <input type="submit" name="login" value="Log In" />
        </form>

        <a class="registration" href="register.php">Create an account</a><br />
    </div>

    <script src="js/jquery-3.5.1.min.js"></script>
    <script src="js/script.js"></script>
</body>
</html>
  • 3
    The header() will not work because it should have to return to the ajax request. There the ajax() is waiting to receive the response. Here the solution is to used JS windows.location to be redirected to another page. – Tufail Ahmad Jun 09 '20 at 08:02
  • 5
    Why: Because you are making a request in the _background_, so you can simple not expect that to have any effect on the “foreground”. The _response_ to this request you get _inside_ of your success callback function, is what the redirect will have affected. – CBroe Jun 09 '20 at 08:02
  • 1
    The whole point of Ajax is to allow you to stay on the same page after making a request to the server. So, wanting to do a redirect during an Ajax call doesn't really make a lot of sense. It doesn't work because it's not what Ajax is intended for, so the browser ignores the location header when it receives it in response to Aja AJAX call – ADyson Jun 09 '20 at 08:35
  • 1
    If you want the user moved to a different page, why are you using AJAX in the first place? – gre_gor Jun 09 '20 at 08:52
  • **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Jun 09 '20 at 10:55
  • Thanks all of Guys for answer the question – kuasa slash Jun 16 '20 at 13:06

1 Answers1

1

PHP redirection won’t work because you are making a ajax call.

Try returning the result and redirect from your script like this.

$(function () {
    jQuery('.userlogin').submit(function(e){
        e.preventDefault();
        var email = jQuery("input[name='email_address']").val();
        var password = jQuery("input[name='password']").val();
        $.ajax({
            'url': 'login.php',
            'type': 'POST',
            'data': {
                'loginajax': '',
                'email': email,
                'password': password

            },
            'success': function (output) {
                console.log(output);
                if (output.status == 'success') {
                    window.location.href = "your url here";//<- your url here
                }
            }
        });
    });
});

Your PHP code should look something like this:

<?php

session_start();

require_once 'functions.php';

if (filter_input(INPUT_POST, 'loginajax')) {
    $result['status'] = 'unsuccessful';
    $result['message'] = 'login unsuccessful.';

    $email = filter_input(INPUT_POST, 'email_address');
    $password = filter_input(INPUT_POST, 'password');

    $sql = "SELECT id,email,password FROM users WHERE email=?";
    $stmt = mysqli_prepare($connection, $sql);
    mysqli_stmt_bind_param($stmt, "s", $email);

    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
    if (mysqli_stmt_fetch($stmt)) {
        if (password_verify($password, $hashed_password)) {
            $_SESSION['login'] = "successful";
            $result['status'] = "success";
            $result['message'] = "login successful.";
        }
    }           
    mysqli_stmt_close($stmt);

    header('Content-Type: application/json');  // <-- header declaration
    echo json_encode($result, true);
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
ImranGalib
  • 114
  • 6