如何将错误消息输入登录模式


How to get error messages into the login modal

我的网站标题中有一个登录模式,当用户单击登录按钮时,它会出现在屏幕上。每当我提交登录表单时,它都会创建一个新的页面,上面有错误。相反,我正在寻找登录模式中出现的错误。有人知道我是怎么做到的吗?

这是login.php

<?php                       //checks pword and email match on database
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Requires two additional files
require ('includes/login_functions.inc.php');
require ('C:'xampp'htdocs'final'includes'db.php');

// Check the login.
list ($check, $data) = check_login($dbc, $_POST['email'], $_POST['pass']);
if ($check) { // OK!
    // Set the session data.
    session_start();
    $_SESSION['id'] = $data['id'];
    $_SESSION['first_name'] = $data['first_name'];

    // Redirect the customer to loggedin page
    redirect_user('loggedin.php');
  } else { // If unsuccessful
        // Assign $data to $errors for login_page.inc.php:
    $errors = $data;
  }
   mysqli_close($dbc); // Close the database connection.
   }
    // Create the page:
     include ('includes/login_page.inc.php');
    ?>

这是login_page.inc

    <link href="css/mystyle.css" rel="stylesheet">
<?php   //displays errors and creates form
    // Include the header:
    $page_title = 'Login';
        if (isset($errors) && !empty($errors)) {
                            echo '<h1><font color="orange">Error!</font>          </h1>
                            <p class="error">The following error(s)  occurred:<br />';
                            foreach ($errors as $msg) {
                        echo " - $msg<br />'n";
                        }
                        echo '</p><p>Please try again.</p>';
                        }

    // Display the form
     ?>

        <div class="modal fade" id="login-modal" tabindex="-1" role="dialog"   aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
          <div class="modal-dialog">
            <div class="loginmodal-container">
                <h1>Login to Your Account</h1><br>
              <form action="login.php" method="post">
                <input type="text" name="email" placeholder="Email Address">
                <input type="password" name="pass" placeholder="Password">
                <input type="submit" name="submit" class="login loginmodal-submit" value="Login">
              </form>
            <div class="login-help">
                    <a>Dont have an account? - </a><a      href="register.php">Register</a> 
                  </div>
                  <?php
                  // Display error messages if there are any
                    /*  if (isset($errors) && !empty($errors)) {
                            echo '<h1><font color="orange">Error!</font>    </h1>
                            <p class="error">The following error(s) occurred:<br />';
                        foreach ($errors as $msg) {
                        echo " - $msg<br />'n";
                        }
                        echo '</p><p>Please try again.</p>';
                        }
               */
              ?>
                </div>
            </div>
          </div>

这是login_functions.inc

 <?php                                  //checks for errors
function redirect_user ($page = 'index.php') {
    $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
    $url = rtrim($url, '/''');
    $url .= '/' . $page;
    header("Location: $url");
    exit(); // Quit the script.
    }

    // Checks the validation of the login.
    function check_login($dbc, $email = '', $password = '') {
    $errors = array(); // Initialize error array.
    // Validate the email address:
    if (empty($email)) {
        $errors[] = 'You forgot to enter your email address.';
    } else {
        $e = mysqli_real_escape_string($dbc, trim($email));
    }
    // Validate the password:
    if (empty($password)) {
        $errors[] = 'You forgot to enter your password.';
    } else {
        $p = mysqli_real_escape_string($dbc, trim($password));
    }
    if (empty($errors)) { // If everything's OK.
        // Retrieve the customer_id and first_name for that email/password combination:
        $q = "SELECT id, first_name FROM user WHERE email='$e' AND password=SHA1('$p')";        
        $r = @mysqli_query ($dbc, $q); // Run the query.
        // Check the result:
        if (mysqli_num_rows($r) == 1) {
            // Fetch the record:
            $row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
            // Return true and the record:
            return array(true, $row);
        } else { // Not a match!
            $errors[] = 'The email address and password entered do not match those on file.';
        }
    } // End of empty($errors) IF.
    // Return false and the errors:
    return array(false, $errors);
    } // End of check_login() function.

这是一个AJAX解决方案。对您的文件进行了许多更改,但评论良好。

login_page.inc中,只有表单受到影响:

<form action="login.php" method="post">
<input type="text" name="email" placeholder="Email Address" id="email">
<input type="password" name="pass" placeholder="Password" id="password">
<input type="submit" name="submit" class="login loginmodal-submit" value="Login">
<div id="login_msg"></div>

然后用以下代码替换整个login.php

// Check if the form has been submitted:
if (isset($_POST['login'])) {
// Requires two additional files
    require ('includes/login_functions.inc.php');
    require ('C:'xampp'htdocs'final'includes'db.php');

// Check the login.
    list ($check, $data) = check_login($dbc, $_POST['email'], $_POST['pass']); //you'll need to validate your email and password before inputing them into this method
    if ($check) { // OK!
        // Set the session data.
        session_start(); //this should be the first thing in your page, if possible in line 1
        $_SESSION['id'] = $data['id'];
        $_SESSION['first_name'] = $data['first_name'];

        die("true"); //stops here and send response to the AJAX Script
        //redirect_user('loggedin.php');
    } else { // If unsuccessful
        // Assign $data to $errors for login_page.inc.php:
        $errors = $data;
    }
    mysqli_close($dbc); // Close the database connection.
}
    // Create the page:
     include ('includes/login_page.inc.php');
}

将JQuery包含到您的项目中。创建一个名为ajax.js的新文件,并将其链接到您的项目。这是ajax.js:的内容

/*
* Login User
*/
$(".loginmodal-submit").click(function (e) {
    e.preventDefault();
    var email = $("#email").val();
    var password = $("#password").val();
    var login = $(".loginmodal-submit").val();
    if (email != "" && password != "") {
        $("login_msg").html("<i class='fa fa-spinner fa-spin fa-lg text-success' style='font-size:20px'></i>");
        $.ajax({
            type: 'POST',
            url: "login.php",
            data: {login: login, email: email, password: password},
            success: function (response)
            {
                if (response == "true") {
                    $(".login-modal").html("<span class='alert alert-success'>Login successful! Redirecting...</span>");
                    window.location.href = "loggedin.php";
                }
                else {
                    $("#login_msg").html('Sorry, your registration was not successful. Please check your details and try again: ');
                    console.log(response)
                }
            }
        });
    }
});