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条)

报告相同问题?

悬赏问题

  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误