PHP登录表单中的简单Ajax无法正常工作

时间:2018-08-29 05:05:30

标签: javascript php jquery html ajax

我创建了一个PHP登录表单,我想在其中添加ajax代码,该代码可以帮助我成功地登录而不添加ajax代码期间加载Windows位。此代码无法正常工作。请帮助我解决此问题,并且有可能我不想在Jquery中的页面后显示登录信息。我的意思是在登录页面之后,我不希望dashboard.php向用户显示。但是我的主要问题是我的代码无法正常工作。请帮助并解决我的问题。

谢谢。

$.ajax({
 method: "POST",
 url: "loginpage.php",
 dataType: "json",
 data: { email: email, password: pass},
success:function(data)
{
if(data.type=='success')
    window.location = 'welcomepage_hideme.php';
else
//server side error from php but now
   alert("Incorrect email or and password");
}
});
<?php
	$msg = "";

	if (isset($_POST['submit'])) {
		$con = new mysqli('localhost', 'research_emailC', 'test123', 'research_phpEmailConfirmation');

		$email = $con->real_escape_string($_POST['email']);
		$password = $con->real_escape_string($_POST['pass']);

		if ($email == "" || $password == "")
			$msg = "Please check your inputs!";
		else {
			$sql = $con->query("SELECT id, password, isEmailConfirmed FROM users WHERE email='$email'");
			if ($sql->num_rows > 0) {
                $data = $sql->fetch_array();
                if (password_verify($password, $data['password'])) {
                    if ($data['isEmailConfirmed'] == 0)
	                    $msg = "Please verify your email!";
                    else {
	                    $msg = "You have been logged in";
                      header("location: welcomepage_hideme.php");
                    }
                } else
	                $msg = "Please check your inputs!";
			} else {
				$msg = "Please check your inputs!";
			}
		}
	}
?>



<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Log In</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
</head>
<body>
	<div class="container" style="margin-top: 100px;">
		<div class="row justify-content-center">
			<div class="col-md-6 col-md-offset-3" align="center">

				<img src="images/logo.png"><br><br>

				<?php if ($msg != "") echo $msg . "<br><br>" ?>

				<form method="post" action="loginpage.php">
					<input class="form-control" name="email" type="email" placeholder="Email..."><br>
					<input class="form-control" name="password" type="password" placeholder="Password..."><br>
					<input class="btn btn-primary" type="submit" name="submit" value="Log In">
				</form>

			</div>
		</div>
	</div>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

从$ _POST数组获取参数的名称中的问题:

$password = $con->real_escape_string($_POST['pass']);

应为:

$password = $con->real_escape_string($_POST['password']);

因为它具有密码名称的形式:

<input class="form-control" name="password" type="password" placeholder="Password..."><br>

答案 1 :(得分:0)

请尝试这个。

Ajax代码

$(document).ready(function(){
            $("#login").submit(function(e) { 
                e.preventDefault(); 
                $.ajax({
                 method: "POST",
                 url: "login.php",
                 dataType: "json",
                 data: $(this).serialize(),
                success:function(data){ 
                    console.log(data);
                if(data.type=='success')
                    window.location = 'welcomepage_hideme.php';
                else
                //server side error from php but now
                   alert("Incorrect email or and password");
                }
                });
            });
           })

HTML代码

<div class="container" style="margin-top: 100px;">
        <div class="row justify-content-center">
            <div class="col-md-6 col-md-offset-3" align="center">
                <form method="post" name="login_form" id="login_form">
                    <input class="form-control" name="email" type="email" placeholder="Email..."><br>
                    <input class="form-control" name="password" type="password" placeholder="Password..."><br>
                    <input class="btn btn-primary" type="submit" name="submit" value="Log In">
                </form>

            </div>
        </div>
    </div>

答案 2 :(得分:0)

此处的孔逻辑不正确。

首先,您应该将php代码从loginpage.php移到fetchLogin.php:

<?php
$result = [ 'status' => false, 'msg' => "Please check your inputs!" ];

if ( isset( $_POST['email'] ) && isset( $_POST['password'] ) ) {
    $con = new mysqli( 'localhost', 'research_emailC', 'test123', 'research_phpEmailConfirmation' );

    $email    = $con->real_escape_string( $_POST['email'] );
    $password = $con->real_escape_string( $_POST['pass'] );

    if ( $email !== "" && $password !== "" ) {
        $sql = $con->query( "SELECT id, password, isEmailConfirmed FROM users WHERE email='$email'" );
        if ( $sql->num_rows > 0 ) {
            $data = $sql->fetch_array();
            if ( password_verify( $password, $data['password'] ) ) {
                if ( $data['isEmailConfirmed'] == 0 ) {
                    $result['msg'] = "Please verify your email!";
                } else {
                    $result['status'] = true;
                    $result['msg']    = "You have been logged in";
                }
            }
        }
    }
}
echo json_encode( $result );

die();

然后更新您的js:

$.ajax({
  method: "POST",
  url: "fetchLogin.php",
  dataType: "json",
  data: { email: email, password: pass}
}).done( function( response ) {
    // code for render response.msg
    if ( ! response.status ) {
        return false;
    } else {
        setTimeout( window.location = "welcomepage_hideme.php", 3000 );
    }
});