Php+jquery+ajax Implement user Login and exit, jqueryajax_php tutorial

Source: Internet
Author: User
Tags jquery library

Php+jquery+ajax Implement user Login and exit, Jqueryajax


User login and exit features are applied in many places, and in some projects, we need to use Ajax to log in, only refresh the page after successful login, thereby enhancing the user experience. This article will use PHP and jquery to implement login and logout functions.

Prepare the database

In this example, we use the MySQL database to create a user table with the following table structure:

CREATE TABLE ' user ' (  ' id ' int (one) ' NOT null auto_increment,  ' username ' varchar (+) ' NOT null COMMENT ' username ',  ' PA ssWOrd ' varchar (+) NOT null COMMENT ' password ',  ' login_time ' int (ten) default NULL COMMENT ' login time ',  ' login_ip ' varchar (3 2) default NULL COMMENT ' login IP ',  ' login_counts ' int (ten) NOT null default ' 0 ' COMMENT ' login count ',  

Then insert a user information data into the users table:

INSERT into ' user ' (' id ', ' username ', ' password ', ' login_time ', ' login_ip ', ' login_counts ')  

index.php

After entering the user name and password, the user prompts the user to log in successfully and displays the relevant login information, and if you click "Exit", you will be logged out to the user login screen.
Enter index.php, if the user is logged in to display the login information, if not logged in the Display login box requires the user to log in.

    

User Login

<?php if (isset ($_session[' user ')) { ?>

<?php echo $_session[' user '];? >, congratulations on your successful login!

You this is <?php echo $_session[' login_counts '];? > Login to this site.

The last time you landed on this site is:

Exit

<?php}else{?>

User name:

Password

<?php}?>

Note that the index.php file header should be added with the statement: session_start; You can also write a nice CSS style for the login box by introducing the jquery library in the head section as well as the global.js, and of course This example has written a simple style, please check the source code.

  

Global.js

The Global.js file includes the jquery code that will be implemented. The first thing to do is to let the input box to get the focus, like Baidu and Google as soon as the open, the mouse cursor in the input box. Use the following code:

$ (function () {   

The next thing to do is to render different styles when the input box gets and loses focus, such as using a different border color in this example, with the following code:

$ ("Input:text,textarea,input:password"). focus (function () {   $ (this). addclass ("Cur_select");}); $ ("Input:text, Textarea,input:password "). blur (function () {   

User login: After the user clicks the login button, first to verify that the user's input cannot be empty, and then send an AJAX request to the background login.php. When the background verifies that the login is successful, the logged-on user information is returned, such as the number of user logins and the last logon time, and the logon failure information if the login fails.

$ (". Btn"). Live (' click ', function () {var user = $ ("#user"). Val ();   var pass = $ ("#pass"). Val (); if (user== "") {$ ('). HTML ("User name cannot be empty!")     "). AppendTo ('. Sub '). FadeOut (2000);     $ ("#user"). focus ();   return false; } if (pass== "") {$ ('). HTML ("Password cannot be empty!")     "). AppendTo ('. Sub '). FadeOut (2000);     $ ("#pass"). focus ();   return false; } $.ajax ({type: "POST", url: "Login.php?action=login", DataType: "JSON", data: {"user": User, "Pass":p     }, Beforesend:function () {$ ('). addclass ("Loading"). HTML ("Logging in ..."). CSS ("Color", "#999"). AppendTo ('. Sub ');         }, Success:function (JSON) {if (json.success==1) {$ ("#login_form"). Remove (); var div = "

"+json.user+", congratulations on your successful login!

You this is the first "+json.login_counts+" login to this site.

The last time to log on to this site is:"+json.login_time+"

Exit

"; $ ("#login"). Append (div); }else{$ ("#msg"). Remove (); $ ('). HTML (json.msg). CSS ("Color", "#999"). AppendTo ('. Sub '). FadeOut (2000); return false; } } }); });

When I am making an AJAX request, the data transfer format uses JSON, the return is JSON data, using JS to parse the JSON data, get the user information after login, and then append to the #login element via append to complete the login operation.
User exit: When clicking "Exit", send an AJAX request to login.php, log off all session, the page back to the login screen.

$ ("#logout"). Live (' click ', Function () {   $.post ("Login.php?action=logout", Function (msg) {     if (msg==1) {        $ ("#result"). Remove ();        var div = "

User name:

Password

"; $ ("#login"). Append (div); }

login.php

According to the request submitted by the foreground, the user entered the user name and password, and compared with the corresponding user name and password in the database, if the match is successful, the new user login information will be updated and the JSON data can be assembled to the foreground.

Session_Start ();  Require_once (' connect.php '); $action = $_get[' action '];   if ($action = = ' Login ') {//Login $user = stripslashes (Trim ($_post[' user '));   $pass = Stripslashes (Trim ($_post[' pass '));     if (Emptyempty ($user)) {echo ' username cannot be empty ';   Exit     } if (Emptyempty ($pass)) {echo ' Password cannot be empty ';   Exit } $MD 5pass = MD5 ($pass);    The password uses MD5 encryption $query = mysql_query ("SELECT * from user where username= ' $user '");    $US = Is_array ($row = mysql_fetch_array ($query)); $ps = $US?   $MD 5pass = = $row [' Password ']: FALSE;     if ($ps) {$counts = $row [' login_counts '] + 1;     $_session[' user '] = $row [' username '];     $_session[' login_time '] = $row [' Login_time '];     $_session[' login_counts '] = $counts; $ip = Get_client_ip ();     Get login IP $logintime = mktime ();     $rs = mysql_query ("Update user set Login_time= ' $logintime ', login_ip= ' $ip ', login_counts= ' $counts '");       if ($rs) {$arr [' success '] = 1; $arr [' msg '] = ' Login successful!       ';   $arr [' user '] = $_session[' user '];    $arr [' login_time '] = Date (' y-m-d h:i:s ', $_session[' login_time ']);     $arr [' login_counts '] = $_session[' login_counts ');       } else {$arr [' success '] = 0;     $arr [' msg '] = ' login failed ';     }} else {$arr [' success '] = 0; $arr [' msg '] = ' username or password error!   '; } Echo Json_encode ($arr);   Output JSON data} elseif ($action = = ' logout ') {//exit unset ($_session);   Session_destroy (); echo ' 1 ';  }

The current station request exits, simply log off the session can be, and return 1 to the foreground JS processing. Note that the above code in GET_CLIENT_IP () is a function to obtain the client IP, limited to the length of the list, you can download the source code to view.

Well, a complete set of user login and exit procedures to complete, the shortcomings are unavoidable, we welcome criticism.

The above mentioned is the whole content of this article, I hope you can like.

http://www.bkjia.com/PHPjc/990541.html www.bkjia.com true http://www.bkjia.com/PHPjc/990541.html techarticle php+jquery+ajax Implementation of user login and exit, Jqueryajax user login and exit features are applied in many places, and in some projects, we need to use the Ajax way to log in, log in as ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.