Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
header() refirect not working on Ajax Login

I am trying to login with ajax. The script is working well and I am getting logged in but I am not getting redirected to the dashboard.php file. Codes are given below. Please try to help me out.

Ajax call

<script type="text/javascript">
$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            username: $("#username").val(),
      password: $("#password").val(),
        };
    $.ajax({
            type: "POST",
            url: "login-process.php",
            data: dataString,
            cache: true,
      beforeSend: function(){
        $('#loading-image').show();
      },
      complete: function(){
        $('#loading-image').hide();
      },
      success: function(html){
        $('.message').html(html).fadeIn(500);
            }
        });
        return false;
    });
});
</script>

login-process.php

<?php
include'config/db.php';
$msg = null;
$date = date('Y-m-d H:i:s');

$uname  = (!empty($_POST['username']))?$_POST['username']:null;
$pass   = (!empty($_POST['password']))?$_POST['password']:null;

if($_POST){
    $stmt = "SELECT * FROM members WHERE mem_uname = :uname";
    $stmt = $pdo->prepare($stmt);
    $stmt->bindValue(':uname', $uname);
    $stmt->execute();
    $checklgn = $stmt->rowCount();
    $fetch = $stmt->fetch();

    if($checklgn > 0){
        if(password_verify($pass, $fetch['mem_pass'])){
            session_start();
            $_SESSION['sanlogin'] = $fetch['mem_id'];
            $msg = "<div class='message-success'>Access Granted! Please wait...</div>";
            $go_login = header("refresh:2; url=dashboard.php");
        }else{
            $msg = "<div class='message-error'>Password mismatch. Please try again!</div>";
        }
    }else{
        $msg = "<div class='message-error'>User not found. Please try again!</div>";
    }
}
echo $msg;
echo $go_login;
?>
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

If you use AJAX to log in, you must use javascript to redirect. Redirecting PHP will only result in the AJAX call being redirected which doesn't produce the desired result.

In your success clause of the ajax request you can add window.location.replace("dashboard.php");

about 4 years ago · Santiago Trujillo Relatório

0

In you ajax success:

use window.location.href="/uri/to/redirect";

setTimeout(function(){
    window.location.href="/uri/to/redirect";
},2000);
about 4 years ago · Santiago Trujillo Relatório

0

You cannot use header PHP function in this situation. You should redirect in your $.ajax function like this:

1) You should return JSON in your login-process.php:

...

$result = array();
if($_POST){
    $stmt = "SELECT * FROM members WHERE mem_uname = :uname";
    $stmt = $pdo->prepare($stmt);
    $stmt->bindValue(':uname', $uname);
    $stmt->execute();
    $checklgn = $stmt->rowCount();
    $fetch = $stmt->fetch();

    if($checklgn > 0){
        if(password_verify($pass, $fetch['mem_pass'])){
            session_start();
            $_SESSION['sanlogin'] = $fetch['mem_id'];
            $result = array(
                'msg' => "<div class='message-success'>Access Granted! Please wait...</div>",
                'redirect' => 'dashboard.php',
            );
        }else{
            $result = array(
                'msg' => "<div class='message-error'>Password mismatch. Please try again!</div>",
            );
        }
    }else{
        $result = array(
            'msg' => "<div class='message-error'>User not found. Please try again!</div>",
        );
    }
}

echo json_encode($result);
exit;

2) You should add parameter dataType into your $.ajax call and process attribute redirect of the server answer (if this attribute exists):

$(document).ready(function () {
    $("#submit").click(function () {
        var dataString = {
            username: $("#username").val(),
            password: $("#password").val(),
        };
        $.ajax({
            dataType: 'json', // <-- set expected dataType here
            type: "POST",
            url: "login-process.php",
            data: dataString,
            cache: true,
            beforeSend: function () {
                $('#loading-image').show();
            },
            complete: function () {
                $('#loading-image').hide();
            },
            success: function (data) {
                $('.message').html(data.message).fadeIn(500);

                // if we have attribute "redirect" in answer
                if(typeof data.redirect !== 'undefined'){
                    // redirect here after 2 seconds
                    setTimeout(function(){
                        document.location.href = data.redirect;
                    },2000);
                }

            }
        });
        return false;
    });
});
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda