简体   繁体   中英

A Better way of doing Fade Out with PHP

I amc creating A Login script with php and javascript.

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.

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
    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.


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:

// 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. Quick example:

PHP Side

<?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:

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. Further, you should be using prepared statements which will safeguard you against SQL injection attacks.

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. 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. That includes things like spaces and new lines.

Now, on to your PHP. You are going to want to output some JSON so that you can check for success or failure in your AJAX.

<?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. 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. Then, we encode the PHP array as JSON, and output it to the response.

//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. The error message at index 0 would correspond to successCode = 0 , and so on. If you weren't going to use sequential successCodes, you could use a javascript object to specify keys corresponding to each error code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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