Header php Location is inserting file instead of redirecting

Asked

Viewed 380 times

2

When I log in to my form, after checking if the user is valid there should be redirection to the home page. But when using header('location: home.php'); is being inserted the contents of the home.php page into the login page. I am using the following ajax method to send the data to php.

function loginRequest() {

 // Declaração de Variáveis
 var delay = 3;
 var usuario   = document.getElementById("txtusuario").value;
 var senha   = document.getElementById("txtsenha").value;
 var btnrqlogin   = document.getElementById("btnrqlogin").id;
 var result = document.getElementById("resultado");
 var xmlreq = CriaRequest();

 // Exibi a imagem de progresso
 result.innerHTML = '<img id="loading-icon" src="./images/eclipse.gif"/>';

 setTimeout(function(){
  // Iniciar uma requisição
  xmlreq.open("GET", "./controllers/controller.php?txtusuario=" + usuario + "&txtsenha=" + senha + "&btnrqlogin=" + btnrqlogin, true);

  // Atribui uma função para ser executada sempre que houver uma mudança de ado
  xmlreq.onreadystatechange = function(){

     // Verifica se foi concluído com sucesso e a conexão fechada (readyState=4)
     if (xmlreq.readyState == 4) {

        // Verifica se o arquivo foi encontrado com sucesso
        if (xmlreq.status == 200) {
           result.innerHTML = xmlreq.responseText;
        }else{
           result.innerHTML = "Erro: " + xmlreq.statusText;
        }
     }
  };
  xmlreq.send(null);
}, delay*1000);
 }

This is my php code.

$usuario = $_GET["txtusuario"];
    $senha = $_GET["txtsenha"];

    //Chama arquivo de conexao com o banco
    require_once("../inc/database.php");

    $consulta = $pdo->prepare(" SELECT id, nome, email FROM tb_usuarios_agencia WHERE email=:email AND senha = :senha");
    $consulta->bindParam(':email', $usuario);
    $consulta->bindParam(':senha', $senha); 
    $consulta->execute();

    while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {

        session_start();
        $_SESSION['id'] = $linha['id'];
        $_SESSION['nome'] = $linha['nome'];
        $_SESSION['email'] = $linha['email'];

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

HTML form.

<div id="resultado">

</div>
<form id="sign_in">
                    <div class="msg">Faça login para iniciar sua sessão</div>
                    <div class="input-group">
                        <span class="input-group-addon">
                            <i class="material-icons">person</i>
                        </span>
                        <div class="form-line">
                            <input type="text" class="form-control" id="txtusuario" name="txtusuario" placeholder="Usuário" required autofocus>
                        </div>
                    </div>
                    <div class="input-group">
                        <span class="input-group-addon">
                            <i class="material-icons">lock</i>
                        </span>
                        <div class="form-line">
                            <input type="password" class="form-control" id="txtsenha" name="txtsenha" placeholder="Senha" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-8 p-t-5">
                            <a href="forgot-password.html">Esqueceu sua senha?</a>
                        </div>
                        <div class="col-xs-4">
                            <!-- onclick="loginRequest();" -->
                            <button id="btnrqlogin" class="btn btn-block bg-pink waves-effect" name="btnrqlogin" onclick="loginRequest();" type="button">ACESSAR</button>
                        </div>
                    </div>
                </form>
  • Aren’t you using ajax? redirecting shouldn’t be done by javascript, rather than tag result

  • It’s the first time I use ajax to send the data to php, I don’t know how to make this redirection by javascript.

  • window.location.href = "home.php"; or window.location.replace("home.php");

  • Unless you are using codeigniter or Laravel

1 answer

1


Ajax requests directed to a div, will fill that div with the return. Soon, make a redirect on the return of Ajax, will just fill this div with the contents of the returned page.

Try to return <script> Ajax does not solve, because it will not be executed, it will only come as string.

To get around this, return from Ajax only the Javascript code and run using eval(). In PHP change the header('location: home.php'); code for:

echo 'location.href="home.php"';

And in Ajax, change the result.innerHTML = xmlreq.responseText; for:

eval(xmlreq.responseText);
  • Now it’s worked out, thank you very much!

Browser other questions tagged

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