weixin_33709590 2016-07-28 17:48 采纳率: 0%
浏览 24

AJAX呼叫未重定向

I've implemented a login page with an AJAX request, that redirects the user depending on the response from the php page loginrequest.php

$.ajax ({

  type: "POST",
  url: "ajax/loginrequest.php",
  data: {
    username: username,
    password:pass
  },

  dataType: "text",

  success: function(html){

    console.log(html); // Prints 'login' or 'fail'

    if(html == 'login'){
      console.log("Yes"); //Never Printed
      window.location.href = 'index.php';
    }
    else if(html == 'fail'){
      alert("Incorrect Username and/or Password");
    }
  }
});

This is the loginrequest.php code that echos login or fail back to the AJAX function

if($count == 1){
  $bool = password_verify($mypassword, $row[1]);

  if($bool == true){
    $_SESSION['user'] = $myusername;
    $_SESSION['division'] = $row[2];
    $return = 'login';
  }
  else{
    $return = 'fail';
  }
}
else{
  $return = 'fail';
}
echo $return;

The console.log inside my success function prints login or fail depending on the credentials, but for some reason the if statement never evaluates to true. My page never redirects and it never displays the alert no matter what. I just uploaded these files to the web server, and they were working fine on WAMP but for some reason it's not working anymore. I tried json_encode() in loginrequest.php but it still wouldn't work. There is nothing wrong with my database call since it returns login or fail depending on the credentials, it's just that if statement in the success function.

What am I doing wrong here?

  • 写回答

2条回答 默认 最新

  • weixin_33709364 2016-07-28 18:21
    关注

    It is very likely that you have a stray whitespace being echo'd by PHP

    Try

    success: function(html){
    
        console.log(html); // Prints 'login' or 'fail'
    
        console.log(html.length); // Is it 5 and 4 respectively?
    
        html = $.trim(html); // if a space is the issue then this should fix it
    
        if(html == 'login'){
            console.log("Yes"); //Never Printed
            window.location.href = 'index.php';
        }
        else if(html == 'fail'){
            alert("Incorrect Username and/or Password");
        }
    }
    
    评论

报告相同问题?