Header location of php is inserting file instead of redirect

2

When I log in to my form, after checking if the user is valid there should be a redirection to the home page. However, when using header('location: home.php'); , the contents of the home.php page are being inserted in the login page. I'm using the following method in ajax 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>
    
asked by anonymous 31.12.2017 / 02:06

1 answer

1

Ajax requests directed to a div , will fill this div with return. So, doing a redirect on Ajax's return will only fill that div with the content of the returned page.

Trying to return% of Ajax% does not solve, since it will not run, it will only come as a string.

To get around this, just return the Ajax JavaScript code and run using <script> . In PHP, change the eval() code to:

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

And in Ajax, change header('location: home.php'); to:

eval(xmlreq.responseText);
    
31.12.2017 / 02:42