weixin_33698043 2015-06-10 11:59 采纳率: 0%
浏览 19

Ajax / PHP登录没有反应

I have received a partially built website and was asked to implement a login system for clients and admins. I am quite new to JS and AJAX and I am having a hard time understanding what the other person has implemented and how I can get it to function properly.

This is the login form where the user can enter in the credientials.

<form name="ajaxform" id="ajaxform" action="auth/ajax-auth.php" method="POST" >
    <h4>Client Login</h4>
        <div id="error"></div>
            <label for="username" class="col-sm-2 control-label">Username</label>
            <input id="username" class="form-control" name='username' placeholder="Username">
            <label for="password" class="col-sm-2 control-label">Password</label>
            <input type="password" class="form-control" id="password" name='password' placeholder="Password">
        </div>
        <div class="modal-footer">
            <button type="button">Close</button>
            <button type="submit" id="loginbtn">Login</button>
        </div>
</form>

Once the form gets submitted it will run ajax-auth.php and also will run an Ajax function. It should then redirect the user who is logging in to either the client side or admin side dependant on their permission level.

The Ajax function looks like this:

$("#ajaxform").submit(function(e)
                      {
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0) {
    $.ajax({
        type: "POST",
        url: "auth/ajax-auth.php",
        data: dataString,
        cache: false,
        beforeSend: function(){ $("#loginbtn").val('Connecting...');},
        success: function(data){
            if(data) {
                alert(data + " Logged in!");

               if(data == "admin"){
                   window.location.href = "/admin/admin.php";
               }
               else if(data == "client"){

                //uncomment when client_home.php page is ready
                //window.location.href = "client_home.php";

                //for now just redirect to homepage
                window.location.href = "index.html";
               }

            } else {
                $("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
                $("#loginbtn").val('Submit')
            }
        }
    });
}

And here is my PHP:

session_start();

error_reporting(E_ALL);                
ini_set('display_errors', 1);          

$username = $_POST['username'];
$password = $_POST['password'];

include '../connection.php';
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";

$result = mysqli_query($dbc, $sql);

    if (mysqli_num_rows($result) == true)
    {
        $_SESSION["username"] = $username;

        $row = mysqli_fetch_array($result);
        if ($row["permission"] == 2)
        {
         $_SESSION["permission"] = 2;
         //Redirect to the admin login page.
         header("Location: ../admin/admin.php");
        }
        else if ($row["permission"] == 1)
        {
        $_SESSION["permission"] = 1;
        $_SESSION["userId"] = $row["user_id"];
        $_SESSION["account"] = $row["account_id"];
        //redirect to the client home page.
        header("Location: ../index.html");   //Change this when ready, for now go to homepage
        }
    }
    else
    {
        echo "User not found!";
        header("Location: ../index.html");
    }

When I enter in a username and password (wrong or right) nothing is happening. If the credentials are wrong my error message should be hitting, and if I am logging in as admin I should be redirected to the admin page, and same with for the client being redirected to the client page.

How/Where am I going wrong here?

The console is not throwing me any errors and even my error message for invalid login creds is not being displayed.

I know I am close, any help is greatly appreciated.

  • 写回答

3条回答 默认 最新

  • weixin_33688840 2015-06-10 12:01
    关注

    You've to give some output in your PHP, because now you're redirecting the request. This won't work for an AJAX request.

    For example:

        if ($row["permission"] == 2)
        {
          $_SESSION["permission"] = 2;
          // Redirect to the admin login page.
          echo 'admin';
        }
        else if ($row["permission"] == 1)
        {
           $_SESSION["permission"] = 1;
           $_SESSION["userId"] = $row["user_id"];
           $_SESSION["account"] = $row["account_id"];
           echo 'client';
        }
    
    评论
  • weixin_33692284 2015-06-10 12:07
    关注

    Try this code

    session_start();
    
    error_reporting(E_ALL);                
    ini_set('display_errors', 1);          
    
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    include '../connection.php';
    $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    
    $sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
    
    $result = mysqli_query($dbc, $sql);
    
        if (mysqli_num_rows($result) == true)
        {
            $_SESSION["username"] = $username;
    
            $row = mysqli_fetch_array($result);
            if ($row["permission"] == 2)
            {
             $_SESSION["permission"] = 2;
             //Redirect to the admin login page.
             echo "admin"; die;
            }
            else if ($row["permission"] == 1)
            {
            $_SESSION["permission"] = 1;
            $_SESSION["userId"] = $row["user_id"];
            $_SESSION["account"] = $row["account_id"];
            //redirect to the client home page.
             echo "client"; die;  //Change this when ready, for now go to homepage
            }
        }
        else
        {
              echo "notFound"; die;
        }
    

    And script is like

     $("#ajaxform").submit(function(e)
                              {
    e.preventDefault();
        var username=$("#username").val();
        var password=$("#password").val();
        var dataString = 'username='+username+'&password='+password;
        if($.trim(username).length>0 && $.trim(password).length>0) {
            $.ajax({
                type: "POST",
                url: "auth/ajax-auth.php",
                data: dataString,
                cache: false,
                beforeSend: function(){ $("#loginbtn").val('Connecting...');},
                success: function(data){
                    if(data=="admin"||data=="client"||) {
                        alert(data + " Logged in!");
    
                       if(data == "admin"){
                           window.location.href = "/admin/admin.php";
                       }
                       else if(data == "client"){
    
                        //uncomment when client_home.php page is ready
                        //window.location.href = "client_home.php";
    
                        //for now just redirect to homepage
                        window.location.href = "client_home.html";
                       }
    
                    } else {
                        $("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
                        $("#loginbtn").val('Submit');
                    }
                }
            });
    }
    
    评论
  • 乱世@小熊 2015-06-10 12:08
    关注

    Instead of this line in your php:

    header("Location: ../index.html");
    

    Use this instead:

    echo $username;
    

    This will return the username to the Ajax request so your javascript can then redirect the user upon a successful login.

    评论

报告相同问题?

悬赏问题

  • ¥15 虚拟机vmnet8 nat模式可以ping通主机,主机也能ping通虚拟机,但是vmnet8一直未识别怎么解决,其次诊断结果就是默认网关不可用
  • ¥20 求各位能用我能理解的话回答超级简单的一些问题
  • ¥15 yolov5双目识别输出坐标代码报错
  • ¥15 这个代码有什么语法错误
  • ¥15 给予STM32按键中断与串口通信
  • ¥15 使用QT实现can通信
  • ¥15 关于sp验证的一些东西,求告知如何解决,
  • ¥35 关于#javascript#的问题:但是我写的只能接码数字和字符,帮我写一个解码JS问题
  • ¥15 prophet运行报错,如何解决?
  • ¥15 用GPU跑pytorch搭建的LSTM的时候出现了奇怪的报错