简体   繁体   English

使用ajaxForm Jquery插件时返回PHP错误

[英]Return PHP error when using ajaxForm Jquery Plugin

I'm trying to make a login script that uses ajaxForm and the validate plugin, but if PHP provides an error, it doesn't know. 我正在尝试制作一个使用ajaxForm和validate插件的登录脚本,但是如果PHP提供了错误,它将不知道。 This is my Javascript 这是我的Javascript

$(function login() {
$("#login").validate({ // initialize the plugin
    // any other options,
    onkeyup: false,
    rules: {
        email: {
            required: true,
            email: true
        },
        password: {
            required: true
        }
    }
});

$('form').ajaxForm({
    beforeSend: function() {
        return $("#login").valid();
    },
    success: function() {
        window.location="index.php";
    },
    error: function(e) {
        alert(e);
    }
});
});

Keep in mind I'm new to JS and there's probably a better way to do this. 请记住,我是JS的新手,也许有更好的方法可以做到这一点。 What I need is, if when the form is submitted but the username or password is wrong, I need it to not redirect, and give the error alert, but this does not work currently. 我需要的是,如果提交表单时,但用户名或密码错误,则我需要它不重定向,并给出错误提示,但这当前不起作用。 I've googled this before, and checked here and so far have found nothing. 我之前在Google上进行过搜索,并在此处进行了检查,到目前为止没有任何发现。

edit: using the below code, it still doesn't work: 编辑:使用下面的代码,它仍然不起作用:

JS JS

   $(function login() {
    $("#login").validate({ // initialize the plugin
        // any other options,
        onkeyup: false,
        rules: {
            email: {
                required: true,
                email: true
            },
            password: {
                required: true
            }
        }
    });

    $("#login").submit(function(e) {
        e.preventDefault();
            $.ajax({
                type : "POST",
                dataType : "json",
                cache : false,
                url : "/doLogin",
                data : $(this).serializeArray(),
                success : function(result) {
                    if(result.result == "success"){
                        window.location = "/index.php";
                    }else if(result.result == "failure"){
                        $("#alert").html("Test");
                    }
               },
                error : function() {
                    $("#failure").show();
                    $(".btn-load").button('reset');
                    $("#email").focus();
                }
            });
    });
    }); 

HTML HTML

<div class="shadowbar">
<div id="alert"></div>
<form id="login" method="post" action="/doLogin">

<fieldset>

 <legend>Log In</legend>
<div class="input-group">
  <span class="input-group-addon">E-Mail</span>

  <input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
  <span class="input-group-addon">Password</span>

  <input type="password" class="form-control" name="password" />
  </div>

</fieldset>

<input type="submit"  class="btn btn-primary" value="Log In" name="submit" />

</form></div>

PHP PHP

public function login() {
    global $dbc, $layout;
    if(!isset($_SESSION['uid'])){
        if(isset($_POST['submit'])){
            $username = mysqli_real_escape_string($dbc, trim($_POST['email']));
            $password = mysqli_real_escape_string($dbc, trim($_POST['password']));
            if(!empty($username) && !empty($password)){
                $query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
                $data = mysqli_query($dbc, $query);
                if((mysqli_num_rows($data) === 1)){
                    $row = mysqli_fetch_array($data);
                    $_SESSION['uid'] = $row['uid'];
                    $_SESSION['username'] = $row['username'];
                    $_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
                    $ip = $_SERVER['REMOTE_ADDR'];
                    $user = $row['uid'];
                    $query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
                    mysqli_query($dbc, $query);
                    setcookie("ID", $row['uid'], time()+3600*24);
                    setcookie("IP", $ip, time()+3600*24);
                    setcookie("HASH", $row['hash'], time()+3600*24);
                    header('Location: /index.php');
                    exit();
                } else {
                    $error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
                    return $error;
                    echo "{\"result\":\"failure\"}";
                }
            } else {
                $error = '<div class="shadowbar">You must enter both your username AND password.</div>';
                return $error;
                $err = "{\"result\":\"failure\"}";
                echo json_encode($err);
            }
            echo "{\"result\":\"success\"}";
        }
    } else {
        echo '{"result":"success"}';
        exit();
    }
    return $error;
}

In your login script, you will need to return errors in json format. 在您的登录脚本中,您将需要以json格式返回错误。

For Example 例如

In your login script, if your query finds a row in the database for that user, echo this: 在您的登录脚本中,如果您的查询在数据库中找到该用户的行,则回显此命令:

echo "{\"result\":\"success\"}";

and if it fails: 如果失败:

echo "{\"result\":\"failure\"}";

You then can parse these in JavaScript like so: 然后,您可以像这样在JavaScript中解析这些内容:

$('form').ajaxForm({
    beforeSend: function() {
        return $("#login").valid();
    },
    success: function(result) {
    if(result.result == "success"){
        window.location = "index.php";
        }else if(result.result == "failure"){
            alert('Failure!');
            }
    error: function(e) {
    alert(e);
    }
}
});

Here's an example of an Ajax script I use to log users into my site, you can use this for reference if needed. 这是我用来将用户登录到我的站点的Ajax脚本的示例 ,如果需要,可以将其用作参考。 This is just to help you get an even broader understanding of what I am talking about: 这只是为了帮助您更深入地了解我在说什么:

I return more than just a success and failure for various reasons such as user intuitiveness, but the gist is there. 由于诸如用户直观性之类的各种原因,我返回的不只是成功和失败,而是要旨。

$("#loginForm").bind("submit", function() {
    $("#invalid").hide();
    $("#disabled").hide();
    $("#error").hide();
    $("#failure").hide();
    $("#blocked").hide();
    var email = document.getElementById("email").value;
    var password = document.getElementById("password").value;
    if(email != "" && password != ""){
        $.ajax({
            type : "POST",
            dataType : "json",
            cache : false,
            url : "/ajax/functions/login",
            data : $(this).serializeArray(),
            success : function(result) {
                if(result.result == "success"){
                    window.location = "/account";
                }else if(result.result == "failure"){
                    $("#invalid").show();
                    $(".btn-load").button('reset');
                    $("#email").focus();
                }else if(result.result == "disabled"){
                    $("#disabled").show();
                    $(".btn-load").button('reset');
                    $("#email").focus();
                }else if(result.result == "blocked"){
                    $("#blocked").show();
                    $(".btn-load").button('reset');
                    $("#email").focus();
               }
           },
            error : function() {
                $("#failure").show();
                $(".btn-load").button('reset');
                $("#email").focus();
            }
        });
    }else{
        $("#error").show();
        $(".btn-load").button('reset');
        $("#email").focus();
    }
    return false;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM