douyouyi8878 2016-01-02 19:13
浏览 32
已采纳

在Ajax php和mysql中读取响应

I can't get the code to work and redirect to 2 different pages depending if the information is correct or not...

So far I have this on my login page:

$(function () {
$('#form').on('submit', function (e) {
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: 'newfile.php',
        data: $('#form').serialize(),
        success: function (response){
        alert(response); 
                    if (success.text="Username or Password incorrect")
                        window.location.href = "index.php"; 
                    else if (success.text="login successful") {
                        window.location.href = "login_success.html";
                    } else {  
                    }
            }
        })
})

and the information Im reading from is (from another page):

<?php    
// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
     die(" Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
$sql="SELECT myusername, mypassword FROM user WHERE myusername = '" . mysqli_real_escape_string($conn, $myusername) . "' and mypassword = '" . mysqli_real_escape_string($conn, $mypassword) . "';";
$result = $conn->query($sql);
if ($result->num_rows >0) {
    echo "login successful";
} else {
    echo "Username or Password incorrect";
}
$conn->close();

?> 
  • 写回答

2条回答 默认 最新

  • duan1227 2016-01-02 19:39
    关注

    I hope this will work for you try this:

    if (response=="usernames or Password incorrect") {
        window.location.href = "index.php";
    } 
    else if (response=="login successful") 
    {
        window.location.href = "login_success.html";
     } 
    else { }
    

    Use this code in ajax success. Actually you are using simple ECHO in PHP and using response.text in ajax success.

    UPDATE:

    you are using = sign for comparing it should be == operator for compare.

    UPDATE 2:

    i suggest to use status as true false not long string in php like:

    if ($result->num_rows >0) {
        echo true;
    } else {
        echo false;
    }
    

    Than in ajax response:

    if(response == true){
    // Success url
    }
    else {
    // failure url
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮