简体   繁体   中英

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. This is my 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. 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.

edit: using the below code, it still doesn't work:

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

<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

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.

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:

$('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. 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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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