简体   繁体   English

用PHP进行淡出的更好方法

[英]A Better way of doing Fade Out with PHP

I amc creating A Login script with php and javascript. 我amc用php和javascript创建一个Login脚本。

What I want to do is log the user in without the page refresh which I have archived so far, With some help from Stack Flow users, I am fairly good with PHP but new to the Javascript client side. 我要做的是在没有刷新页面的情况下登录用户,到目前为止,我没有归档页面刷新。在Stack Flow用户的帮助下,我对PHP相当满意,但是对Javascript客户端来说却是新手。

Anyway, When the user enters the correct data and the session gets started how do I get it to call the fade out function? 无论如何,当用户输入正确的数据并且会话开始时,如何调用淡出功能?

Heres the PHP Side 继承人的PHP方面

<?php
    require "../core/database.php";

    //lets create some veriables to use, This way is shorter
    $username = strip_tags(trim($_POST['user_login']));
    $password = strip_tags(trim($_POST['pass_login']));
    $md5_pass = md5($_POST['pass_login']);

    $user_login = mysql_real_escape_string($username);
    $pass_login = mysql_real_escape_string($md5_pass);

    if (($user_login) && ($password)) {
    //Connect to the database to fetch the users username and password
    $select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
    $user_rows = mysql_fetch_array($select_user);
    $username_row = $user_rows['username'];
    $password_row = $user_rows['password'];

        if(($username_row==$user_login)  && ($md5_pass==$password_row)) {
        //All user information is correct, Now start the session

        //I HAVE CALLED IT HERE HOPING THERE,S A BETTER WAY OF DOING THIS. IT WILL CAL
        echo "
        Yes, Now we can start the session right here, when your ready.

        <script> 
        $('#field').fadeOut();
        </script>";

        } else {

        echo "The username or password you entered is incorrect";
        }

    } else {
    echo "<b>Blank Fields</b> <br>
    You must enter A Username/Password Combination";
    }



?>

Incase yous need it, there is the client side aswill (modified by some users to make the functionality better) 如果您需要它,则有客户端意愿(某些用户对其进行了修改,以使功能更好)

$(document).ready(function() {
    // Make a function that returns the data, then call it whenever you
    // need the current values
    function getData() {
        return {
            user_login: $('#user_login').val(),
            pass_login: $('#pass_login').val()

        }
    }


        function loading(e) {
        $('#content').html('Loading Data');
    }

    function check(e) {
        e.preventDefault();
        $.ajax({

            url: 'ajax/check.php',
            type: 'post',
            data: getData(), // get current values
            success: function (data) {
                $('#content').html(data);
            }
        });
    }

    // Don't repeat so much; use the same function for both handlers
    $('#field').keyup(function(e) {
        if (e.keyCode == 13) {
    var username = $('#user_login').val();

        loading(e);
        check(e);

        }
    });

    $('#submit').click(function(e) {
        if (e.keyCode != 13) {
        loading(e);
        check(e);
        } 


    });

});

Since PHP is Server Side and Java Script controls the Client side, Probably the best way to do or call it is this way, But its worth A ask anyway. 因为PHP是服务器端,而Java脚本控制着客户端,所以做或调用它的最佳方法可能就是这种方式,但是无论如何它还是值得一问的。


Besides this everything is working out well. 除此之外,一切都进行得很好。

If you want you can help change the way loading data is coded/works, But the functionality is working perfectly so theres not much need. 如果您希望可以帮助更改加载/编码/工作数据的方式,但是该功能可以正常运行,因此没有太多需求。

The ajax success method needs to check the response from the server to see if login was successful and then take the appropriate action: ajax成功方法需要检查服务器的响应,以查看登录是否成功,然后采取适当的措施:

// php    
if(($username_row==$user_login)  && ($md5_pass==$password_row)) {
            //All user information is correct, Now start the session

            echo 'correct';

            } else {

            echo 'The username or password you entered is incorrect';
            }

// js
function check(e) {
        e.preventDefault();
        $.ajax({
            url: 'ajax/check.php',
            type: 'post',
            data: getData(), // get current values
            success: function (data) {
                if (data === 'correct') {
                  $('#field').fadeOut();
                } else {
                  $('#content').html(data);
                }
            }
        });
    }

Returning JSON instead of raw HTML is much more flexible. 返回JSON而不是原始HTML更加灵活。 Quick example: 快速示例:

PHP Side PHP方面

<?php
require "../core/database.php";

$json = array('success' => false, 'error' => null);

$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);

$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);

if (($user_login) && ($password)) {

    $select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
    $user_rows = mysql_fetch_array($select_user);
    $username_row = $user_rows['username'];
    $password_row = $user_rows['password'];

    if(($username_row==$user_login)  && ($md5_pass==$password_row)) {
        $json['success'] = true;
    } 
    else {
        $json['error'] = "The username or password you entered is incorrect";
    }

} else {
    $json['error'] = "<b>Blank Fields</b> <br>You must enter A Username/Password Combination";
}

echo json_encode($json);

Your AJAX function: 您的AJAX功能:

function check(e) {
    e.preventDefault();
    $.ajax({

        url: 'ajax/check.php',
        type: 'post',
        data: getData(), // get current values
        success: function (data) {
            var loginResult = JSON.parse(data);
            if(loginResult.success){

                //Login successful - fade out whatever form or fields
                //that you want to
                $('#field').fadeOut();

            } else{
                //Add error message to an error div or whatever
                $('#error').html(loginResult.error);
            }
        }
    });
}

I'll start by saying that your PHP should be using the newer mysqli_* functions or the PDO object for all of your database queries. 首先,您的PHP应该对所有数据库查询使用较新的mysqli_ *函数或PDO对象。 Further, you should be using prepared statements which will safeguard you against SQL injection attacks. 此外,您应该使用准备好的语句 ,以保护您免受SQL注入攻击。

Another thing to note is that in a PHP file that is not going to output anything to the browser, or in other words, is just going to run some code, you don't need a closing tag. 需要注意的另一件事是,在一个PHP文件中,该文件不会向浏览器输出任何内容,或者换句话说,仅用于运行一些代码,因此不需要结束标记。 In fact, you don't want a closing tag. 实际上,您不需要结束标记。 That is because anything after the closing tag will get sent to the browser, which will get included in the response of your AJAX success function. 这是因为在结束标记之后的所有内容都将发送到浏览器,这将包含在AJAX成功函数的响应中。 That includes things like spaces and new lines. 其中包括空格和换行符。

Now, on to your PHP. 现在,转到您的PHP。 You are going to want to output some JSON so that you can check for success or failure in your AJAX. 您将要输出一些JSON,以便可以检查AJAX中的成功或失败。

PHP PHP

<?php
    require "../core/database.php";

    //lets create some veriables to use, This way is shorter
    $username = strip_tags(trim($_POST['user_login']));
    $password = strip_tags(trim($_POST['pass_login']));
    $md5_pass = md5($_POST['pass_login']);

    $user_login = mysql_real_escape_string($username);
    $pass_login = mysql_real_escape_string($md5_pass);

    //Create an array to represent our JSON data.
    $json = array(
        "successCode" => 0
    );

    if (($user_login) && ($password)) {
        //Connect to the database to fetch the users username and password
        $select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
        $user_rows = mysql_fetch_array($select_user);
        $username_row = $user_rows['username'];
        $password_row = $user_rows['password'];

        if(($username_row==$user_login)  && ($md5_pass==$password_row)) {
            //All user information is correct, Now start the session
            //echo "Yes, Now we can start the session right here, when your ready."
            $json['successCode'] = 0;
        } else {
            //echo "The username or password you entered is incorrect";
            $json['successCode'] = 1;
        }

    } else {
        //echo "<b>Blank Fields</b> <br>
        //You must enter A Username/Password Combination";
        $json['successCode'] = 2;
    }

    //Set that our content type is JSON
    header("Content-type: application/json");
    echo json_encode($json); //Convert the PHP array to JSON and echo it as the response.

In our PHP, we have created a $json array which will story the successCode that we will be responding to the client. 在我们的PHP,我们已经创建了一个$json阵列将故事successCode ,我们将响应客户端。 This will tell the client if the login was a success or failure, and even what type of failure occurred. 这将告诉客户端登录是成功还是失败,甚至发生什么类型的失败。 It will then be up to the client to decide how to display that success or failure to the user. 然后由客户端决定如何向用户显示该成功或失败。 This allows multiple applications to use the same server side source, but display the errors differently if desired. 这允许多个应用程序使用相同的服务器端源,但是如果需要,则以不同的方式显示错误。

At the end of the PHP, we have set the header Content-type to specify that we are sending back application/json to the client. 在PHP的末尾,我们设置了标头Content-type来指定将application/json发送回客户端。 Then, we encode the PHP array as JSON, and output it to the response. 然后,我们将PHP数组编码为JSON,并将其输出到响应。

jQuery/Javascript jQuery的/ JavaScript的

//Let's define different messages depending on what status code we get on the client.
var errorMessages = [
    "Yes, Now we can start the session right here, when your ready.",
    "The username or password you entered is incorrect",
    "<b>Blank Fields</b><br />You must enter A Username/Password Combination"
];

function check(e) {
    e.preventDefault();
    $.ajax({
        url: 'ajax/check.php',
        type: 'post',
        data: getData(), // get current values
        success: function (data) {
            //First, make sure that data and data.successCode are defined.
            if (data && data.successCode) {
                //Here, you are getting back the JSON data from the login call.
                $('#content').html(errorMessages[data.successCode]);

                //If the successCode is 0, which means it was successful, then we want to fade out the #field div.
                if (data.successCode == 0) {
                    $('#field').fadeOut();
                }
            } else {
                //There must've been a server error. You'd handle that here.
            }
        }
    });
}

Why put the error messages on the client instead of the server? 为什么将错误消息放在客户端而不是服务器上? Because it allows you to easily change how the error messages are displayed, without having to touch the server side code. 因为它使您可以轻松更改错误消息的显示方式,而无需触摸服务器端代码。 The server just outputs an error code, and the client decides how to handle that code. 服务器仅输出错误代码,而客户端则决定如何处理该代码。

The Javascript array, errorMessages , defines the error messages corresponding to their index in the array. Javascript数组errorMessages定义了与其在数组中的索引相对应的错误消息。 The error message at index 0 would correspond to successCode = 0 , and so on. 索引0处的错误消息将对应于successCode = 0 ,依此类推。 If you weren't going to use sequential successCodes, you could use a javascript object to specify keys corresponding to each error code. 如果您不打算使用顺序成功代码,则可以使用javascript对象来指定与每个错误代码相对应的键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM