duan19780629 2014-07-20 01:20
浏览 58
已采纳

jQuery AJAX请求PHP登录无法正常工作

So I'm trying to do an inline login whenever the PHP $_SESSION['logged_in'] variable is not set. (this variable is set when I log a user in) The problem is that I can get my script to work when using multiple pages with header redirects, but trying to remain on the same page via AJAX requests to the login.php file is failing. Here's a look at my code.

the login form itself...

<?php 
      include ('global.inc.php');
        if ( $_SESSION['logged_in'] == 1 ) {
            echo '<form id="addNoteForm"><label for="title">Title</label><input id="noteTitle" type="text" class="form-control" name="title"/>
                <label for="content">Content</label><textarea id="noteContent" class="form-control" rows="20" name="content"></textarea>
                <input type="submit" id="addNoteButton" class="btn btn-primary" value="Add Note" />
                <button class="btn" onclick="cancelAddNote()">Cancel</button>
            </form>';
        }
        else {

            echo '<form id="loginForm" action="login.php" method="get" role="form">
                <div class="form-group">
                <label for="username">Username</label>
                <input id="loginUsername" type="text" class="form-control" name="username" value="'.$username.'">
                </div>
                <div class="form-group">
                <label for="password">Password</label>
                <input id="loginPassword" type="password" class="form-control" name="password" value="'.$password.'">
                </div>
                <button type="submit" class="btn btn-default" name="submit-login">Login</button>
                </form>';
            }
        ?>

jQuery AJAX request script

  jQuery(function() {
    jQuery('#loginForm').submit(function(e){
        e.preventDefault();

        var username = jQuery('#loginUsername').val();
        var password = jQuery('#loginPassword').val();

        jQuery.ajax({
            type: 'GET',
            url: 'login.php',
            data: 'username='+username+'&password='+password,
            success: function(data) {
                setTimeout(function(){
                   window.location.reload();
                }, 1000);

            },
            error: function(data) {
                console.log('AJAX login failed. Returned data = '+data);
            }
        });
    });
});

here is the login.php file

<?php

        header("Access-Control-Allow-Origin: *");
        require_once (__DIR__.'/includes/global.inc.php');

        $userTools = new UserTools();

        if ( isset($_GET['username']) ) {
            $username = $_GET['username'];
            $password = $_GET['password'];
        }

        if ( $userTools->login($username, $password) ) {
            return true;
        }

        else {
            return false;
        }
    ?>

the global.inc.php file

require_once (__DIR__.'/../classes/Note.class.php');
require_once (__DIR__.'/../classes/NoteTools.class.php');
require_once (__DIR__.'/../classes/User.class.php');
require_once (__DIR__.'/../classes/UserTools.class.php');
require_once (__DIR__.'/../classes/Database.class.php');


// connect to the database
$db = new Database();

// initialize UserTools object
$userTools = new UserTools();

// start the session
session_start();

// refresh session variables if already logged in
if ( isset($_SESSION['logged_in'])) {
    $user = unserialize($_SESSION['user']);
    $_SESSION['user'] = serialize($userTools->getUser($user->id));
}

and finally, the login script of my UserTools.class.php

public function login($username, $password) {

        $hashedPassword = md5($password);

        $database = new Database();
        $database->query('SELECT * FROM users WHERE username = :username AND password = :password');

        $database->bind(':username', $username);
        $database->bind(':password', $hashedPassword);

        $user = $database->single();

        $user = new User($user);

        if ( $database->rowCount() == 1) {
            $_SESSION['user'] = serialize($user);
            $_SESSION['login_time'] = time();
            $_SESSION['logged_in'] = 1;
            return true;
        }

        else {
            return false;
        }
    }

I feel like I'm overlooking something minor here and need a fresh set of eyes to take a look at it. Like I said before, when I had a separate login.php file that upon successful login did a header redirect to a "welcome page", I had no problems with it. I think I'm having an issue with how I'm returning data to my jQuery function through AJAX. I dunno. Any help is GREATLY appreciated!

  • 写回答

2条回答 默认 最新

  • doucang2831 2014-08-10 19:27
    关注

    Turns out it was a modsec issue set on the server by my web host. All is working now. Thanks to everyone for their help!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料