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");
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀