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 三菱变频器模块怎么检测触发
  • ¥30 求一下解题思路,完全不懂。
  • ¥30 关于#硬件工程#的问题:求一下解题思路
  • ¥15 运筹学对偶单纯行法构造扩充问题
  • ¥20 XP系统的老电脑一开机就提示找不到rundll.exe,付费求解
  • ¥15 milvus查询出来的score怎么转换成0-1之间的相似性
  • ¥15 lvgl V9移植到linux开发板
  • ¥15 VB.net中在窗体中创建一个button控件来关闭窗体,但是提示错误,我该怎么办
  • ¥15 网上下载好的程序但是arduinoIDE编程报错,运行不了,哪里出错了,能具体给改一下吗
  • ¥15 Sharepoint JS开发 付费技术指导