返回AJAX成功和错误

时间:2015-07-17 09:28:09

标签: php jquery ajax

我已经构建了一个使用AJAX提交表单数据的登录脚本。

PHP部分在没有AJAX的情况下工作正常。但该系统不适用于AJAX实现。

它始终显示以下消息,即使PHP文件返回 true [正确的用户名&密码] ...好像Jquery中的 if 条件不起作用。

  

用户名/密码不正确

HTML结果分区

<div id="user-result" align="center"></div>

Jquery

<script type="text/javascript">
    $(document).ready(function () {
        var form = $('#loginform');
        form.submit(function (ev) {
            ev.preventDefault();
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                cache: false,
                data: form.serialize(),
                success: function (data) {
                    if (data == "true") {
                        $("#user-result").html("<font color ='#006600'> Logged in | Redirecting..</font>").show("fast");
                        setTimeout(
                            function () {
                                window.location.replace("index.php");
                            }, 1500);
                    } else {
                        $("#user-result").html("<font color ='red'> Incorrect Username/Password</font>").show("fast");
                    }

                }

            });
        });
    }); 
</script>

fn_login.php

<?php
{
    session_start();
    include_once 'db_connect.php';

    if (isset($_POST))
     {
        $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
        $logpwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

        $stmt = $conn->prepare("SELECT password FROM manager WHERE email = ? LIMIT 1");
        $stmt->bind_param("s", $email);


        $stmt->execute();
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($password);
        $stmt->fetch();


        // Check if a user has provided the correct password by comparing what they typed with our hash
        if (password_verify($logpwd, $password))
        {
            $sql = "SELECT * from manager WHERE email LIKE '{$email}' LIMIT 1";
            $result = $conn->query($sql);
            $row=mysqli_fetch_array($result);
            $id = $row['id'];
            $conn->query("UPDATE manager SET lastlogin = NOW() WHERE id = $id");

            $_SESSION['manager_check'] = 1;
            $_SESSION['email'] = $row['email'];
            $_SESSION['fullname'] = $row['fullname'];
            $_SESSION['designation'] = $row['designation'];
            $_SESSION['id'] = $row['id'];
            echo "true";
        }
         else {
            die();
        }
     }
}

?>      

有人可以指出代码/练习中的错误。

EDIT

Just Tried禁用AJAX,当用户名/传递正确时,PHP文件正常回显true

2 个答案:

答案 0 :(得分:2)

?>

后面有空格

因此,AJAX响应在true之后有空格。

<强>解决方案:

从PHP文件的末尾删除?>

它不会影响任何PHP功能。

而你的AJAX响应将没有空格。

从PHP文件末尾排除结束标记?>是现代PHP框架和CMS的标准做法。

调试AJAX的提示:

1)始终在或Chrome上使用Firefox(带Firebug Add)。

2)使用Firebug的Console标签,检查哪些AJAX请求。

3)在这里,您可以看到输入参数,标题和最重要的响应。

4)因此,简而言之,您可以调试整个AJAX请求生命周期。

答案 1 :(得分:0)

您可以从php代码回显json_encode(array('success'=>true))并使用if在jquery中修改if(data.success){}条件。您的修改后的代码将变为

<?php
{
    session_start();
    include_once 'db_connect.php';

    if (isset($_POST))
     {
        $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
        $logpwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

        $stmt = $conn->prepare("SELECT password FROM manager WHERE email = ? LIMIT 1");
        $stmt->bind_param("s", $email);


        $stmt->execute();
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($password);
        $stmt->fetch();


        // Check if a user has provided the correct password by comparing what they typed with our hash
        if (password_verify($logpwd, $password))
        {
            $sql = "SELECT * from manager WHERE email LIKE '{$email}' LIMIT 1";
            $result = $conn->query($sql);
            $row=mysqli_fetch_array($result);
            $id = $row['id'];
            $conn->query("UPDATE manager SET lastlogin = NOW() WHERE id = $id");

            $_SESSION['manager_check'] = 1;
            $_SESSION['email'] = $row['email'];
            $_SESSION['fullname'] = $row['fullname'];
            $_SESSION['designation'] = $row['designation'];
            $_SESSION['id'] = $row['id'];
            echo json_encode(array('success'=>true));
        }
         else {
            die();
        }
     }
}

AND JQuery成为

<script type="text/javascript">
    $(document).ready(function () {
        var form = $('#loginform');
        form.submit(function (ev) {
            ev.preventDefault();
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                cache: false,
                data: form.serialize(),
                success: function (data) {
                    if (data.success) {
                        $("#user-result").html("<font color ='#006600'> Logged in | Redirecting..</font>").show("fast");
                        setTimeout(
                            function () {
                                window.location.replace("index.php");
                            }, 1500);
                    } else {
                        $("#user-result").html("<font color ='red'> Incorrect Username/Password</font>").show("fast");
                    }

                }

            });
        });
    }); 
</script>