Page and data redirection with Ajax

Asked

Viewed 343 times

0

Test scenario

I have a page from login.php, that checks the user and password with ajax, sending the data via post to the file valida.php.

The valida.php, when the authentication works, should redirect to another page, taking the data in $_POST. But if you use a header for example, it returns error instead of success.


Archives

login.php

<!DOCTYPE html>
<html>
<head>
    <?php require_once 'html\head.php' ?>

    <script type="text/javascript">

        function login(){
            var myData = $("#login").serialize();
            arquivo = "valida.php";
            $.ajax({
                type: 'post',
                data: myData,
                url: arquivo,
                success:function(response){
                    //alert(response);
                    $('#ret').html(response).show();
                },
                error:function(xhr, ajaxOptions, thrownError){
                    alert('error');
                }
            });
        }

    </script>

</head>
<body>

    <nav class="navbar navbar-light bg-light">
        <a class="navbar-brand" href="#">
            <img src="assets/img/truck.svg" width="30" height="30" class="d-inline-block align-top" alt="">
            Teste
        </a>
        <form id="login" class="form-inline">
            <input class="form-control mr-sm-2" type="text" name="user" placeholder="Usuário" aria-label="User">
            <input class="form-control mr-sm-2" type="password" name="pswd" placeholder="Senha" aria-label="Pass">
            <button class="btn btn-outline-warning my-2 my-sm-0" type="button" onclick="login();">Entrar</button>
        </form>
    </nav>

    <div class="container">
        <div id="ret"></div>


    </div>

</body>
</html>

valida.php

set_time_limit(10);

$user = filter_input(INPUT_POST,'user');
$pswd = filter_input(INPUT_POST,'pswd');

if (isset($user) && isset($pswd)) {
    
    if ($user == 'rbz' && $pswd == 123) {

        header('location: ok.php');
        
    } else {

        echo '<br><div class="alert alert-danger alert-dismissible fade show" role="alert">
        <strong>Atenção!</strong> Usuário ou senha incorretos.
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
        </button>
        </div><br>';
    }

} else {

    echo "preencha os 2 campos";
}

  • How could you redirect the page, keeping the data in $_POST?
  • Why don’t you send by $_SESSION[] ?

  • There are 2 cases. I don’t have a Septssion, but could already start on valida.php and redirect (would still have the problem of redirecting (do on return success!? would be ideal!? ), and has the option of not opening the valida.php, then keep the question doubt.

  • There is no way to redirect post, so what you want there is no way to do. Why you need this data to be forwarded as post?

  • I set up your environment here to do some tests, I came across 2 things, keeping the answer 302, ajax works correctly but making the return 200 ajax not even get the error. or anything on the console.

1 answer

1

The way you’re doing the job header()will not be interpreted and redirection will not occur in response to an asynchronous request.

This is because response headers have already been sent before PHP interprets the function header().

To get around the situation, you can check if there is any output sent to the browser when its function header() is invoked.

One way to do this is by using the function headers_sent().

After validating the login and password, you could do something like:

if (!headers_sent()) {
    header('Location: ok.php');
    exit;
}else{
    echo '<script type="text/javascript">window.location.href="ok.php";</script>';
    exit;
}

Basically the script will check if any header has already been sent as a response. If none has been sent, PHP will try redirecting with header() otherwise it will generate a message like this:

"Cannot Modify header information - headers already sent"

Because some headlines have already been sent.

But to get around this problem, the else will be executed and PHP will attempt redirect with Javascript.

However, this would still not be the best way to redirect your request response.

You can allow the file valida.php send only a bulletin reply stating whether the access credentials are valid or not. Or, you can send an array with user information in case of positive authentication and return an empty array in case of negative authentication.

And with this, use Javascript / jQuery to perform redirect.

Or even perform other actions other than specifically redirecting.

The advantages of doing this with Javascript is the freedom that will guarantee you.

On the other hand, as a disadvantage, it is the fact that Javascript can be disabled in the browser and this will make login authentication not work. However, you can inform that it is necessary to keep Javascript enabled in the browser when the user disables it at some point for some reason using the tag <noscript>E uma mensagem aqui informando para ativar o Javascript</noscript>.

And to conclude, this would be the other way to perform redirect after authentication:

login.php

<!DOCTYPE html>
<html>
<head>
    <?php require_once 'html\head.php' ?>

    <script type="text/javascript">

        function login(){
            var myData = $("#login").serialize();
            arquivo = "valida.php";
            $.ajax({
                type: 'post',
                data: myData,
                url: arquivo,
                success:function(response){
                    if(response.autenticado){
                        window.location.href = 'ok.php';
                    }else{
                        $('#ret').html(response.mensagem).show();
                    }
                },
                error:function(xhr, ajaxOptions, thrownError){
                    $('#ret').html(response.mensagem).show();
                }
            });
        }

    </script>

</head>
<body>

    <nav class="navbar navbar-light bg-light">
        <a class="navbar-brand" href="#">
            <img src="assets/img/truck.svg" width="30" height="30" class="d-inline-block align-top" alt="">
            Teste
        </a>
        <form id="login" class="form-inline">
            <input class="form-control mr-sm-2" type="text" name="user" placeholder="Usuário" aria-label="User">
            <input class="form-control mr-sm-2" type="password" name="pswd" placeholder="Senha" aria-label="Pass">
            <button class="btn btn-outline-warning my-2 my-sm-0" type="button" onclick="login();">Entrar</button>
        </form>
    </nav>

    <div class="container">
        <div id="ret"></div>


    </div>

</body>
</html>

valida.php

set_time_limit(10);

$user = filter_input(INPUT_POST,'user');
$pswd = filter_input(INPUT_POST,'pswd');

if (isset($user) && isset($pswd)) {

    if ($user == 'rbz' && $pswd == 123) {
        $response = array('autenticado' => true, 'mensagem' => '');
    }else{
        $response = array('autenticado' => false, 'mensagem' => 'Atenção! Usuário ou senha incorretos');
    }

}else{
    $response = array('autenticado' => true, 'mensagem' => 'Atenção! Usuário ou senha incorretos');
}

return json_encode($response);

This script was just to exemplify and guide you on how to succeed with your redirect. Of course you can improve this and manipulate the result of your authentication more freely with Javascript / jQuery.

  • "because the reply headers have already been sent before" when exactly the file valida.php headers were sent before the function header?

  • Pardon. Allow me to correct, in the file cited by the author of the question, not in my suggestion. My lack of attention.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.