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 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd