通过PHP调用外部文件中定义的Javascript函数

时间:2018-05-14 20:15:30

标签: javascript php

我有一个网页,我有一个简单的登录表单,包含用户名和密码文本字段。

我使用javascript外部文件验证登录表单,如果javascript代码返回true,则提交登录表单,否则将通过名为{javascript的{​​{1}}函数显示错误消息{1}}我写的。

如果表单已提交,然后使用displayErrorBlock(),我会验证用户名和密码。如果用户名/密码组合不正确或数据库中不存在,我想从PHP代码中调用相同的javascript函数(displayErrorBLock)。< / p>

要做到这一点,我回应这个

PHP

这会导致else { // if username/password combination is incorrect echo '<script>displayErrorBlock("Incorrect Username/Password")</script>'; } 错误,因为displayErrorBLock undefined已加载到我网页的javascript标记的末尾。

问题

如何调用外部文件中定义的 body函数javascript

这是外部(displayErrorBlock)文件中定义的displayErrorBlock函数

js

修改

这是我的整个网页

function displayErrorBlock(errorMsg) {
    'use strict';
    let errorBlock = document.querySelector('.error-msg-block');
    errorBlock.style.display = 'block';
    errorBlock.firstElementChild.textContent = errorMsg;

    setTimeout(function () {
        errorBlock.style.height = '48px';
    }, 10);
}

更新问题

我遇到了一些问题。

  1. 当我尝试登录<?php require 'DbConnection.php'; // if login button is clicked if(isset($_POST['login-btn'])) { $username = $_POST['username-field']; $password = $_POST['password-field']; verifyLoginCredentials($username, $password); } // verify admin login credentials function verifyLoginCredentials($username, $password) { global $dbConnect; $query = 'SELECT full_name, username, password FROM admins WHERE username = ?'; $statement = $dbConnect->prepare($query); if($statement) { $statement->bind_param('s', $username); $statement->execute(); $resultSet = $statement->get_result(); // since there will be only one row returned at max, no need of a loop $row = $resultSet->fetch_assoc(); if($row != null) { $adminFullName = $row['full_name']; $adminUsername = $row['username']; $adminPassword = $row['password']; // if username/password is correct start session and store // username, password, full name in the session and login // admin to his account if($username === $adminUsername && password_verify($password, $adminPassword)) { session_start(); $_SESSION['current_admin_fullname'] = $adminFullName; $_SESSION['current_admin_username'] = $adminUsername; $_SESSION['current_admin_password'] = $adminPassword; //take current admin to admin dashboard header('Location:admin dashboard.php'); } else { // if username/password combination is incorrect echo '<script>displayErrorBlock("Incorrect Username/Password")</script>'; } } else { // if username doesn't exists in the database echo '<script>displayErrorBlock("Entered Username isn\'t registered")</script>'; } } } ?> <!DOCTYPE html> <html> <head lang="en"> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="../Resources/Bootstrap v4.1/css/bootstrap.min.css"/> <link rel="stylesheet" href="../CSS/admin login.css"/> <link rel="stylesheet" href="../CSS/common.css"/> <title>Admin Login</title> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-12 navbar-container"> <nav class="top-navbar"> <img src="../Resources/images/logo.png" alt="logo"/> <p>Admin Panel</p> </nav><!--end of navbar--> </div><!--end of first column--> </div><!--end of first row--> <div class="row"> <div class="col-sm-4 login-form-container"> <p class="error-msg-block"> <span></span> </p> <form class="login-form" method="post" action="admin login.php" onsubmit="return validateForm()"> <p>Welcome Back!</p> <div class="form-group username-group"> <label for="username-field">Username</label> <div class="input-group"> <div class="input-group-prepend"> <div class="input-group-text"> <img src="../Resources/images/envelope.png" alt="envelope image"/> </div> </div> <input class="form-control" id="username-field" type="text" name="username-field" id="username-field" placeholder="Username"/> </div> </div><!--end of first form group--> <div class="form-group password-group"> <label for="password-field">Password</label> <div class="input-group"> <div class="input-group-prepend"> <div class="input-group-text"> <img src="../Resources/images/lock.png" alt="lock image"/> </div> </div> <input class="form-control" id="password-field" type="password" name="password-field" id="password-field" placeholder="Password"/> </div> </div><!--end of second form-group--> <input type="submit" class="btn" id="login-btn" name="login-btn" value="Login"/> </form><!--end of login form--> </div><!--end of first column--> </div><!--end of second row--> </div><!--end of container--> <!--CDN versions of JQuery and Popper.js--> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script> <script src="../Resources/Bootstrap v4.1/js/bootstrap.min.js"></script> <script src="../Javascript/admin login form validation.js"></script> </body> </html> .responseText方法内的控制台时,我将整个网页作为回复。

  2. 通过ajax,php文件中的主.onLoad

    提交表单时

    if statement

    永远不会评估为true,因此php代码不会执行。

  3. 我在这里做错了什么?

    这是我的PHP代码

    if(isset($_POST['login-btn'])) {....}

    这是我的相关javascript代码

    <?php
    
        require 'DbConnection.php';
    
        // if login button is clicked
        if(isset($_POST['login-btn'])) {
            $username = $_POST['username-field'];
            $password = $_POST['password-field'];
            echo '<script>alert(\'form submitted\')</script>';   <---- this alert is never invoked
            verifyLoginCredentials($username, $password);
        }
    
        // verify admin login credentials
        function verifyLoginCredentials($username, $password) {
            global $dbConnect;
            $query = 'SELECT full_name, username, password FROM admins WHERE username = ?';
            $statement = $dbConnect->prepare($query);
    
            if($statement) {
                $statement->bind_param('s', $username);
                $statement->execute();
                $resultSet = $statement->get_result();
    
                // since there will be only one row returned at max, no need of a loop
                $row = $resultSet->fetch_assoc();
    
                if($row != null) {
                    $adminFullName = $row['full_name'];
                    $adminUsername = $row['username'];
                    $adminPassword = $row['password'];
    
                    // if username/password is correct start session and store
                    // username, password, full name in the session
                    if($username === $adminUsername && password_verify($password, $adminPassword)) {
                        session_start();
                        $_SESSION['current_admin_fullname'] = $adminFullName;
                        $_SESSION['current_admin_username'] = $adminUsername;
                        $_SESSION['current_admin_password'] = $adminPassword;
                    }
                    else { // if username/password combination is incorrect
                        echo 'Incorrect Username/Password Combination';
                    }
                } else { // if username doesn't exists in the database
                    echo 'Entered username isn\'t registered';
                }
            } else {
                echo 'Error while preparing sql query';
            }
        }
    
    ?>
    

1 个答案:

答案 0 :(得分:1)

在HTML结构的<head></head>元素中,添加以下代码:

<script type="text/javascript">
// Wait for the document to load
document.addEventListener("DOMContentLoaded", function(event) {
    // Add event listener to form submit
    document.querySelector(".login-form").addEventListener("submit", function(e) {
        // Prevent the form from being submitted
        e.preventDefault();

        // Perform displayErrorBlock() function
        validateForm();

        // Create native XMLHttpRequest object
        var xhr = new XMLHttpRequest();

        // Set POST request header leaving second parameter empty because PHP
        // code is in the same file.
        xhr.open('POST', '');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
            // Everything was ok, handle response
            if (xhr.readyState === 4 && xhr.status === 200) {
                // Succesful login. Redirect user
                if(xhr.responseText === 'succes'){
                    window.location.replace("https://your_website.com/admin dashboard.php");
                }
                // Wrong username / password
                else if(xhr.responseText === 'errorUserPass'){
                    displayErrorBlock("Incorrect Username/Password");
                }
                // User doesn't exist
                else if(xhr.responseText === 'errorNotRegistered'){
                    displayErrorBlock("Entered Username isn't registered");
                }
                // Something else was returned by PHP
                else {
                    displayErrorBlock("Unknown error: "+ xhr.responseText);
                }
            }
            // Request failed, alert error
            else if (xhr.status !== 200) {
                alert('Request failed.  Returned status of ' + xhr.status);
            }
        };
        xhr.send(new FormData(document.querySelector(".login-form")));
    });
});
</script>

我对大多数专栏作了评论,以解释他们的所作所为。接下来,您必须将表单更改为:

<form class="login-form" method="post" action="">

由于我们已在表单上创建了自定义事件处理程序,因此可以从那里控制所有内容。因此,不再需要在HTML结构中执行此操作。

最后,您需要更改PHP代码,使其返回正确的响应:

header('Location:admin dashboard.php');替换为echo 'succes';
echo '<script>displayErrorBlock("Incorrect Username/Password")</script>';替换为echo 'errorUserPass';echo '<script>displayErrorBlock("Entered Username isn\'t registered")</script>';替换为echo 'errorNotRegistered';

正如我在评论中所说,自从我在原生JS中做到这一点以来已经有一段时间了。我无法真正测试此代码,所以如果出现问题请告诉我。或者至少它应该帮助你走向正确的方向。