This is the HTML with form:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Login</title>
    <link rel="stylesheet" href="css/index.css" type="text/css" media="screen" />
    <script type="text/javascript" src="js/jquery-1.10.2.min.js" charset="utf-8"></script>
    <script type="text/javascript" src="js/login.js" charset="utf-8"></script>
    <script src="../htdocs/SpryAssets_index/SpryMenuBar.js" type="text/javascript"></script>
    <link href="../htdocs/SpryAssets_index/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
    <link type="text/css" rel="stylesheet" href="includes/css/index.css" />
</head>

<body>
    <div class="container">
        <?php
            include ('includes/header.html')
        ?>
        <br /><br />
        <h1>Login</h1>
        <p id="results"></p>
        <form action="login_ajax.php" method="post" id="login">
            <p id="emailP">Email Address: <input type="text" name="email" id="email" /><span class="errorMessage" id="emailError">Please enter your email address!</span></p>
            <p id="passwordP">Password: <input type="password" name="password" id="password" /><span class="errorMessage" id="passwordError">Please enter your password!</span></p>
            <p><input type="submit" name="submit" value="Login!" /></p>
</form>
        <div class="footer">
        <?php
            include ('includes/footer.html')
        ?>
        </div>
    </div>    
</body>
</html>

This is the handler login_ajax.php:

<?php
if (isset($_POST['email'], $_POST['password'])) {
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    function check_login($dbc, $email = 'email', $pass = 'pass') {
    $errors = array(); //Intialize the error array.
        if (empty($email)) {
            $errors[] = 'You forgot to enter your email address.';
        } else {
            $e = filter_var($email, FILTER_SANITIZE_EMAIL);
        }
        if (empty($pass)) {
            $errors[] = 'You forgot to enter your password.';
        } else {
            $p = mysqli_real_escape_string($dbc, trim($pass));
        }
        if (empty($errors)) {
            $q = "SELECT first_name, last_name FROM users WHERE email='$e' AND pass=SHA1('$p')";
            $r = mysqli_query ($dbc, $q);
            if (mysqli_num_rows($r) == 1) {
                $row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
                echo 'CORRECT';
            } else {
                $errors[] = 'The email address and password entered do not match those on file.';
                echo 'INCORRECT';
            }               
        session_start();//START A SESSION HERE.
        $_SESSION['first_name'] = $data['first_name'];
        $_SESSION['last_name'] = $data['last_name'];    
        }
    }
check_login($dbc, $_POST['email'], $_POST['password']);
} else {
    echo 'INVALID_EMAIL';
}
} else {
echo 'INCOMPLETE';
}
?>

This is the Javascript that handles the echo login.js:

// Script 15.10 - login.js
// This script is included by login.php.
// This script handles and validates the form submission.
// This script then makes an Ajax request of login_ajax.php.

// Do something when the document is ready:
$(function() {

// Hide all error messages:
$('.errorMessage').hide();

// Assign an event handler to the form:
$('#login').submit(function() {

    // Initialize some variables:
    var email, password;

    // Validate the email address:
    if ($('#email').val().length >= 6) {

        // Get the email address:
        email = $('#email').val();

        // Clear an error, if one existed:
        $('#emailP').removeClass('error');

        // Hide the error message, if it was visible:
        $('#emailError').hide();

    } else { // Invalid email address!

        // Add an error class:
        $('#emailP').addClass('error');

        // Show the error message:
        $('#emailError').show();

    }

    // Validate the password:
    if ($('#password').val().length > 0) {
        password = $('#password').val();
        $('#passwordP').removeClass('error');
        $('#passwordError').hide();
    } else {
        $('#passwordP').addClass('error');
        $('#passwordError').show();
    }

    // If appropriate, perform the Ajax request:
    if (email && password) {

        // Create an object for the form data:
        var data = new Object();
        data.email = email;
        data.password = password;

        // Create an object of Ajax options:
        var options = new Object();

        // Establish each setting:
        options.data = data;
        options.dataType = 'text';
        options.type = 'get';
        options.success = function(response) {

            // Worked:
            if (response == 'CORRECT') {

                // Hide the form:
                $('#login').hide();

                // Show a message:
                $('#results').removeClass('error');
                $('#results').text('You are now logged in!');

            } else if (response == 'INCORRECT') {
                $('#results').text('The submitted credentials do not match those on file!');
                $('#results').addClass('error');
            } else if (response == 'INCOMPLETE') {
                $('#results').text('Please provide an email address and a password!');
                $('#results').addClass('error');
            } else if (response == 'INVALID_EMAIL') {                   
                $('#results').text('Please provide your email address!');
                $('#results').addClass('error');
            }

        }; // End of success.
        options.url = 'login_ajax.php';

        // Perform the request:
        $.ajax(options);

    } // End of email && password IF.

    // Return false to prevent an actual form submission:
    return false;

}); // End of form submission.

}); // End of document ready.

This form is returning an INCOMPLETE from the PHP handler which the Javascript is returning as "Please provide an email address and a password!".

有帮助吗?

解决方案

Heres my suggestion for you. Hopefully this makes sense and works for you. Please try to understand what is happening rather than just copy and hope it works. Your form, on submit, gets sent to the JS file. This grabs the form values, uses JSON to send them to your php file which processes everything and returns a response, either true or false. If false, the js file will display your errors on screen and add classes etc. If true you can get it to redirector do whatever you want.

HTML form...

<h1>Login</h1>
        <p id="results"></p>    
<form action="login_ajax.php" method="post" id="login" onsubmit="jsquicksub(this); return false;>
                <p id="emailP">Email Address: <input type="text" name="email" id="email" /><span class="errorMessage" id="emailError">Please enter your email address!</span></p>
                <p id="passwordP">Password: <input type="password" name="password" id="password" /><span class="errorMessage" id="passwordError">Please enter your password!</span></p>
                <p><input type="submit" name="submit" value="Login!" /></p>
    </form>

In your login.js

// hide the div where the error reporting gets displayed on load of the page
$(document).ready(function() {
    $('#results').hide();
});    

var gb_ajaxbusy = false;

function jsquicksub(po_form) {

    if (gb_ajaxbusy)
        return false;

    gb_ajaxbusy = true;


    var lo_request = {};
    // go through each and every form element and assign to variable
    lo_request.e = $(po_form).find('#email').val();
    lo_request.p = $(po_form).find('#password').val();

    $(po_form).fadeTo(200, 0.3);

    $.getJSON('/login.php', lo_request, function(po_result) { // php form processing field

        gb_ajaxbusy = false;
        $(po_form).fadeTo(0, 1);

        if (!po_result.success) {
            $('#results').show();
            document.getElementById('results').innerHTML = po_result.content; 

// inserts errors in specified div. can use alert if wanted
// do your thing with adding classes etc if you want to
            return false;
        }
        // replace form with thankyou message/redirect somewhere or whatever you want to do

        // empty results element
        $('#results').hide();

    });

} // end jsquicksub()

Then in your login.php file ....

// function gets passed values after validation and returns a message to the user on screen - gets passed back to JS file which then returns stuff to the screen
function jsonreturn($pb_success, $ps_content = null) {

    $lo_result = (object) array('success'=>$pb_success, 'content'=>$ps_content);

    ob_clean();
    echo json_encode($lo_result);
    exit;

} // end jsonreturn()

    // these values are recieved from the javascript function
    $ps_email = isset($_GET['e'])? $_GET['e']: null;
    $ps_password = isset($_GET['p'])? $_GET['p']: null;


    if(empty($ps_email) OR empty($ps_password)) {
         // run your check_login stuff in here
         // use jsonreturn(false, 'message') for error OR when everything is fine and you have set the session, use jsonreturn(true, 'complete');
    }
else {
    jsonreturn(false, 'Your error message in here which gets added to the id="results" p tag');
}

其他提示

There are new ways to code, faster and better ; you are programing not in a very good way, everything is mixed so it get confused.

Your php handler is testing for POSTed variables, but you've set the javascript to send by GET.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top