找到你要的答案

Q:Php Login With Ajax

Q:PHP和Ajax登录

I am trying to make a login with ajax, I want the user to login and if the username(email) and password are correct the page should use the method .load to load the page "perfil.php", that I won't post the code since it isn't relevant. However nothing is happening even if i type random user/password.

I just started with SESSION's and AJAX so any help would be appreciated, BTW i don't need answers talking about hashing the password at this moment.

index

<?php
    session_start();
    if(!empty($_SESSION['login_user'])){
        header('Location: user/perfil.php');
    }
?>

<form class="form-signin" id="form-signin" method="post" action="">
<h2 class="form-signin-heading">Sign in</h2>
<input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required="true" autofocus="true">
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required="true">
<div class="checkbox">
    <label>
        <input type="checkbox" value="remember-me"> Lembrar-me
    </label>
</div>
<button id="entrar" class="btn btn-lg btn-primary btn-block" type="submit" name="submit">Sign in</button>

login.php

<?php
include_once '../config/db.php';
session_start();
if (isSet($_POST['email']) && isSet($_POST['password'])) {
    try {
        $pdo = Database::connect();
        $email = $_POST['email'];
        $password = $_POST['password'];

        $query= "SELECT id FROM utilizador WHERE email = '$email' and pass = '$password'";

        $stmt = $pdo->prepare($query);
        $stmt->execute();  
        $num=$stmt->rowCount();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if($num > 0)
            $_SESSION['login_user']=$row['id'];
            echo $row['id'];    
        }
        Database::disconnect();
    }
    catch (Exception $e){
        echo 'Exception: ',  $e->getMessage(), "\n";
    }
}
?>

javascript

$('#entrar').click(function()
{
    var email = $("#inputEmail").val();
    var password = $("#inputPassword").val();
    var dataString = 'email='+email+'&password='+password;
    if($.trim(username).length>0 && $.trim(password).length>0)
    {
        $.ajax({
            type: "POST",
            url: "user/login.php",
            data: dataString,
            cache: false,
            beforeSend: function(){ $("#entrar").val('A entrar...');},
            success: function(data){
                if(data)
                {
                    showNotas();
                    $('#form-signin').fadeOut('slow', function(){
                        $("#section-1 .container").load("user/perfil.php").fadeIn(1500).delay(5000);
                        $("#section-1 span").text("Perfil");
                    });
                    $('#notas').show();
                }
                else
                {
                    $("#entrar").val('Sign in')
                    $("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
                }
            }
        }); 
    }
return false;
});

EDIT: Chrome dev isn't displaying any error

I am trying to make a login with ajax, I want the user to login and if the username(email) and password are correct the page should use the method .load to load the page "perfil.php", that I won't post the code since it isn't relevant. However nothing is happening even if i type random user/password.

我刚开始用会话和Ajax等任何帮助将不胜感激,顺便说一句,我不需要答案谈论哈希密码在这一刻。

指数

<?php
    session_start();
    if(!empty($_SESSION['login_user'])){
        header('Location: user/perfil.php');
    }
?>

<form class="form-signin" id="form-signin" method="post" action="">
<h2 class="form-signin-heading">Sign in</h2>
<input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required="true" autofocus="true">
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required="true">
<div class="checkbox">
    <label>
        <input type="checkbox" value="remember-me"> Lembrar-me
    </label>
</div>
<button id="entrar" class="btn btn-lg btn-primary btn-block" type="submit" name="submit">Sign in</button>

login.php

<?php
include_once '../config/db.php';
session_start();
if (isSet($_POST['email']) && isSet($_POST['password'])) {
    try {
        $pdo = Database::connect();
        $email = $_POST['email'];
        $password = $_POST['password'];

        $query= "SELECT id FROM utilizador WHERE email = '$email' and pass = '$password'";

        $stmt = $pdo->prepare($query);
        $stmt->execute();  
        $num=$stmt->rowCount();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if($num > 0)
            $_SESSION['login_user']=$row['id'];
            echo $row['id'];    
        }
        Database::disconnect();
    }
    catch (Exception $e){
        echo 'Exception: ',  $e->getMessage(), "\n";
    }
}
?>

JavaScript

$('#entrar').click(function()
{
    var email = $("#inputEmail").val();
    var password = $("#inputPassword").val();
    var dataString = 'email='+email+'&password='+password;
    if($.trim(username).length>0 && $.trim(password).length>0)
    {
        $.ajax({
            type: "POST",
            url: "用户/ login.php",
            data: dataString,
            cache: false,
            beforeSend: function(){ $("#entrar").val('A entrar...');},
            success: function(data){
                if(data)
                {
                    showNotas();
                    $('#form-signin').fadeOut('slow', function(){
                        $("#section-1 .container").load("user/perfil.php").fadeIn(1500).delay(5000);
                        $("#section-1 span").text("Perfil");
                    });
                    $('#notas').show();
                }
                else
                {
                    $("#entrar").val('Sign in')
                    $("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
                }
            }
        }); 
    }
return false;
});

EDIT: Chrome dev isn't displaying any error

answer1: 回答1:

Chrome Developer Tools may not be displayed any errors in your console, however, go along to the Network tab, click on the XHR Request (the file AJAX will ping to make the request to log a user in, I'm assuming it'll be user/login.php, and go to the Preview and/or Response tab and see post back what they say to us. It may well just be a PHP error, not JavaScript

Chrome开发者工具可能无法在您的控制台,显示任何错误,然而,走到网络选项卡,在XHR请求点击(文件Ajax将平使要求用户登录,我假设它将用户/ login.php,去预览和/或响应选项卡,看后回来,他们对我们说什么。它很可能是一个错误,没有JavaScript

answer2: 回答2:

It is very difficult to answer your question since we don't know what the problem is. So I just describe a systematic approach on how to solve such a situation.

  • You have to test every single part of your code to determine, where the problem lies. That means: Javascript, PHP, Database.
  • You should start with the PHP. Maybe first don't use data from POST but just hardcode an email & password and then see if the query against the database delivers the expected result. Or query the database but don't use data from POST.
  • If PHP just returns nothing make sure you have turned on error reporting. You otherwise will not know why something isn't working. This can be done by adding error_reporting(E_ALL); at the top of your PHP code, above all includes and requires.
  • If this is working, try doing it with post. First submit your form without Javascript. You could use the action attribute of the form and just submit it normally. Or you use something like curl or postman. See what PHP says with error reporting on.
  • Now do the same POST with your Ajax script. You could add console.log(variable) statements and watch in the console if anything goes wrong.

Oh, and while writing all this I spotted a missing { in your code. This could be the problem... ;)

<?php
include_once '../config/db.php';
session_start();
if (isSet($_POST['email']) && isSet($_POST['password'])) {
    try {
        $pdo = Database::connect();
        $email = $_POST['email'];
        $password = $_POST['password'];

        $query= "SELECT id FROM utilizador WHERE email = '$email' and pass = '$password'";

        $stmt = $pdo->prepare($query);
        $stmt->execute();  
        $num=$stmt->rowCount();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if($num > 0) { // THIS WAS MISSING
            $_SESSION['login_user']=$row['id'];
            echo $row['id'];    
        }
        Database::disconnect();
    }
    catch (Exception $e){
        echo 'Exception: ',  $e->getMessage(), "\n";
    }
}
?>

很难回答你的问题,因为我们不知道问题是什么。所以我只是描述了一个系统的方法来解决这种情况。

  • You have to test every single part of your code to determine, where the problem lies. That means: Javascript, PHP, Database.
  • You should start with the PHP. Maybe first don't use data from POST but just hardcode an email & password and then see if the query against the database delivers the expected result. Or query the database but don't use data from POST.
  • If PHP just returns nothing make sure you have turned on error reporting. You otherwise will not know why something isn't working. This can be done by adding error_reporting(E_ALL); at the top of your PHP code, above all includes and requires.
  • If this is working, try doing it with post. First submit your form without Javascript. You could use the action attribute of the form and just submit it normally. Or you use something like curl or postman. See what PHP says with error reporting on.
  • Now do the same POST with your Ajax script. You could add console.log(variable) statements and watch in the console if anything goes wrong.

哦,在写这一切的时候,我在你的代码中发现了一个缺失的{。这可能是问题…;)

<?php
include_once '../config/db.php';
session_start();
if (isSet($_POST['email']) && isSet($_POST['password'])) {
    try {
        $pdo = Database::connect();
        $email = $_POST['email'];
        $password = $_POST['password'];

        $query= "SELECT id FROM utilizador WHERE email = '$email' and pass = '$password'";

        $stmt = $pdo->prepare($query);
        $stmt->execute();  
        $num=$stmt->rowCount();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if($num > 0) { // THIS WAS MISSING
            $_SESSION['login_user']=$row['id'];
            echo $row['id'];    
        }
        Database::disconnect();
    }
    catch (Exception $e){
        echo 'Exception: ',  $e->getMessage(), "\n";
    }
}
?>
answer3: 回答3:

UPDATED

html (changed checkbox, added id)

...
<label>
    <input id="rememberMe" type="checkbox" value="remember-me"> Lembrar-me
</label>
...

js

$('#entrar').click(function( event )
{
    event.preventDefault();

    var email = $("#inputEmail").val();
    var password = $("#inputPassword").val();
    var rememberMe = 'unchecked';

    if ( $('#rememberMe').is(':checked') ){
        rememberMe = 'checked';
    } else {
        rememberMe = 'unchecked';
    }

    $.ajax({
        url: 'user/login.php',
        type: 'POST',
        data:{
            email:email,
            password:password,
            rememberMe:rememberMe
        },
        success: function(data){
            alert(data);
        }
    });
});

user/login.php

session_start();

header('Content-type: text/html; charset=utf-8');

$email = $_POST['email'];
$password = $_POST['password'];
$rememberMe = $_POST['rememberMe'];

$_SESSION['test_email'] = $email;
$_SESSION['test_password'] = $password;

echo 'sessions: <br>' . $_SESSION['test_email'] . ' | ' . $_SESSION['test_password'] . ' | remember me: ' . $rememberMe;

UPDATED

add this code to the top of login.php file to reveal php errors

ini_set('display_errors', 1);
error_reporting(~0);

更新

HTML(更改复选框,添加ID)

...
<label>
    <input id="rememberMe" type="checkbox" value="remember-me"> Lembrar-me
</label>
...

js

$('#entrar').click(function( event )
{
    event.preventDefault();

    var email = $("#inputEmail").val();
    var password = $("#inputPassword").val();
    var rememberMe = 'unchecked';

    if ( $('#rememberMe').is(':checked') ){
        rememberMe = 'checked';
    } else {
        rememberMe = 'unchecked';
    }

    $.ajax({
        url: '用户/ login.php',
        type: 'POST',
        data:{
            email:email,
            password:password,
            rememberMe:rememberMe
        },
        success: function(data){
            alert(data);
        }
    });
});

用户/ login.php

session_start();

header('Content-type: text/html; charset=utf-8');

$email = $_POST['email'];
$password = $_POST['password'];
$rememberMe = $_POST['rememberMe'];

$_SESSION['test_email'] = $email;
$_SESSION['test_password'] = $password;

echo 'sessions: <br>' . $_SESSION['test_email'] . ' | ' . $_SESSION['test_password'] . ' | remember me: ' . $rememberMe;

更新

添加此代码对login.php文件顶部显示PHP错误

ini_set('display_errors', 1);
error_reporting(~0);
answer4: 回答4:

I'm not sure why but i changed the $('#entrar').click(function( event ) to function entrar() and moved it outside the $(document).ready(function() and it worked.. Thanks everyon anyway, Cheers

I'm not sure why but i changed the $('#entrar').click(function( event ) to function entrar() and moved it outside the $(document).ready(function() and it worked.. Thanks everyon anyway, Cheers

javascript  php  ajax  session  pdo