-1

console

im trying to redirect after a successful login, code as follows:

//if success (if there is a row)
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();    
// make the server ready for a session
session_start();
$_SESSION['userId'] = $row['user_id'];
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['user_role'] = $row['user_role'];
$_SESSION['status'] = "ok";
session_write_close();


//get user_role for proper redirection
$iUserRole = $row['user_role'];
if($iUserRole==0){

header('Location: ../admin.php');  
exit();
} else if($iUserRole==1){

  header('Location: ../user.php');
  exit();
} else if($iUserRole==2){

  header('Location: ../partner.php');

  exit();
}

i can see in the browser that the admin.php is downloaded.

the php is called with:

$.ajax({
        url: 'ajax_api/login_auth.php',
        type: 'POST',
        data: {
            "sEmail": sEmail,
            "sPassword": sPassword
        },
    })
    .fail(function() {
        console.log("jquery ajax login_auth error");
    }).success(function(data) {
        console.log(data);

    });

and the console.log(data) logs the entire html page html/text.

Community
  • 1
  • 1
Kasper Sølvstrøm
  • 270
  • 1
  • 2
  • 22
  • php shoud return the url in response body and `window.location = data` in js – cske Apr 24 '15 at 22:03
  • that answer doesn't really help me, i want a fix to my problem, not a new solution – Kasper Sølvstrøm Apr 24 '15 at 22:10
  • 1
    an ajax response with location header will not never erver redirect the loaded page, that's way you need another solution [check this](https://stackoverflow.com/questions/503093/how-can-i-make-a-redirect-page-using-jquery?rq=1) – cske Apr 24 '15 at 22:14
  • so if i login with a form and submit the redirect will work from the header()? – Kasper Sølvstrøm Apr 24 '15 at 22:19
  • yes, that will work, you shoud decide between html form&header location or ajax & js location rewrite – cske Apr 24 '15 at 22:22

1 Answers1

0

You can not redirect a page from ajax call. In this case you need to pass url to you ajax response and then redirect page using javascript

PHP

//if success (if there is a row)
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();    
// make the server ready for a session
session_start();
$_SESSION['userId'] = $row['user_id'];
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['user_role'] = $row['user_role'];
$_SESSION['status'] = "ok";
session_write_close();


//get user_role for proper redirection
$iUserRole = $row['user_role'];
if($iUserRole==0){

echo "{Full URL}";  
exit();
} else if($iUserRole==1){

  echo "{Full URL}";
  exit();
} else if($iUserRole==2){

  echo "{Full URL}";

  exit();
}

Javascript

// similar behavior as an HTTP redirect
window.location.replace("{URL}");

// similar behavior as clicking on a link
window.location.href = "{URL}";
Manish Shukla
  • 1,355
  • 2
  • 8
  • 21