PHP + jQuery + Ajax for user login and exit
PHP + jQuery + Ajax for user login and exit
This article uses Ajax to enhance the user experience by refreshing new logon and logout. If the user is logged on, the user-related logon information is displayed; otherwise, the logon form is displayed.
The user logon and exit functions are used in many places. In some projects, we need to use Ajax to log on. After Successful Logon, we only refresh the page to improve the user experience. This article uses PHP and jQuery to implement the login and exit functions.
Prepare Database
In this example, we use the Mysql database to create a user table with the following table structure:
?
1 2 3 4 5 6 7 8 9 |
Create table 'user '( 'Id' int (11) not null auto_increment, 'Username' varchar (30) not null comment 'username ', 'Password' varchar (32) not null comment 'Password ', 'Login _ time' int (10) default null comment 'logon time ', 'Login _ ip' varchar (32) default null comment 'logon ip ', 'Login _ counts' int (10) not null default '0' comment' login times ', Primary key ('id ') ) ENGINE = MyISAM default charset = utf8; |
Insert a piece of user information data into the user table:
?
1 2 |
Insert into 'user' ('id', 'username', 'Password', 'login _ time', 'login _ ip', 'login _ counts ') VALUES (1, 'Demo', 'fe01ce2a7fbac8fafaed7c982a04e229 ', '','', 0 ); |
Index. php
After entering the user name and password, the user is prompted that the user has successfully logged on, and relevant logon information is displayed. If you click "exit", the user logon page is displayed.
Go to index. php. If the user is logged on, the logon information is displayed. If the user is not logged on, the logon box is displayed, asking the user to log on.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<Div id = "login"> <H3> User Logon <? Php If (isset ($ _ SESSION ['user']) { ?> <Div id = "result"> <P> <strong> <? Php echo $ _ SESSION ['user'];?> </Strong> congratulations! </P> <P> This is the <span> <? Php echo $ _ SESSION ['login _ counts'];?> </Span> log on to this site. </P> <P> The Last Time I log on to this site was: <span> <? Php echo date ('Y-m-d H: I: s', $ _ SESSION ['login _ time']);?> </Span> </p> <a href = '#' id = 'logout'> [logout] </a> </p> </Div> <? Php} else {?> <Div id = "login_form"> <P> <label> user name: </label> <input type = "text" class = "input" name = "user" id = "user"/> </p> <P> <label> password: </label> <input type = "password" class = "input" name = "pass" id = "pass"/> </P> <Div class = "sub"> <Input type = "submit" class = "btn" value = "login"/> </Div> </Div> <? Php }?> </Div> |
Note that in index. the PHP file header should be added with the statement session_start. At the same time, the jquery library and global. js, you can also write a beautiful CSS style for the login box, of course, this example has slightly written a simple style, please refer to the source code.
?
1 2 |
<Script type = "text/javascript" src = "js/jquery. js"> </script> <Script type = "text/javascript" src = "js/global. js"> </script> |
Global. js
The global. js file includes the jquery code to be implemented. The first thing to do is to let the input box get the focus. When you open it like Baidu and google, the mouse cursor is inside the input box. The Code is as follows:
?
1 2 3 |
$ (Function (){ $ ("# User"). focus (); }); |
The next step is to present different styles when the input box gets or loses the focus. For example, to use different border colors in this example, the code is as follows:
?
1 2 3 4 5 6 |
$ ("Input: text, textarea, input: password"). focus (function (){ $ (This). addClass ("cur_select "); }); $ ("Input: text, textarea, input: password"). blur (function (){ $ (This). removeClass ("cur_select "); }); |
User Logon: After clicking the logon button, you must first verify that the user input cannot be blank and then send an Ajax request to the background login. php. After the background verifies that the logon is successful, the system returns the logon user information, such as the number of user logins and the last logon time. If the logon fails, the system returns the logon Failure Information.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
$ (". Btn"). live ('click', function (){ Var user = $ ("# user"). val (); Var pass = $ ("# pass"). val (); If (user = ""){ $ ('<Div id = "msg"/> 'hangzhou.html ("user name cannot be blank! "). AppendTo ('. sub'). fadeOut (2000 ); $ ("# User"). focus (); Return false; } If (pass = ""){ $ ('<Div id = "msg"/> 'hangzhou.html ("the password cannot be blank! "). AppendTo ('. sub'). fadeOut (2000 ); $ ("# Pass"). focus (); Return false; } $. Ajax ({ Type: "POST ", Url: "login. php? Action = login ", DataType: "json ", Data: {"user": user, "pass": pass }, BeforeSend: function (){ $ ('<Div id = "msg"/>'). addClass ("loading" Login .html ("logging on..." Login .css ("color", "#999 ") . AppendTo ('. sub '); }, Success: function (json ){ If (json. success = 1 ){ $ ("# Login_form"). remove (); Var div = "<div id = 'result'> <p> <strong>" + json. user + "</strong>. Congratulations! </P> <P> you have logged on to the <span> "+ json. login_counts +" </span> website. </P> <P> the last time you log on to this site is: <span> "+ json. login_time +" </span> </p> <p> <A href = '#' id = 'logout'> [exit] </a> </p> </div> "; $ ("# Login"). append (div ); } Else { $ ("# Msg"). remove (); $ ('<Div id = "errmsg"/> '0000.html(json.msg0000.css ("color", "#999"). appendTo ('. sub ') . FadeOut (2000 ); Return false; } } }); }); |
When I make an Ajax request, the data transmission format is json, and the returned data is also json data. I use JS to parse the json data and obtain the user information after logon, append to the # login element through append to complete the logon operation.
User Exit: When you click "exit", send an Ajax request to login. php, log out all sessions in the background, and return to the logon page.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$ ("# Logout"). live ('click', function (){ $. Post ("login. php? Action = logout ", function (msg ){ If (msg = 1 ){ $ ("# Result"). remove (); Var div = "<div id = 'login _ form'> <p> <label> User name: </label> <Input type = 'text' class = 'input' name = 'user' id = 'user'/> </p> <P> <label> password: </label> <input type = 'Password' class = 'input' name = 'pass' Id = 'pass'/> </p> <Div class = 'sub'> <input type = 'submit 'class = 'btn' value = 'login '/> </div> </Div> "; $ ("# Login"). append (div ); } }); }); |
Login. php
Based on the request submitted by the front-end, the user name and password entered by the user are obtained at login and compared with the corresponding user name and password in the database. If the comparison is successful, then, the new login information is updated and json data is assembled and sent to the front-end.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
Session_start (); Require_once ('connect. php '); $ Action = $ _ GET ['action']; If ($ action = 'login') {// log on $ User = stripslashes (trim ($ _ POST ['user']); $ Pass = stripslashes (trim ($ _ POST ['pass']); If (emptyempty ($ user )){ Echo 'user name cannot be blank '; Exit; } If (emptyempty ($ pass )){ Echo 'password cannot be blank '; Exit; } $ Md5pass = md5 ($ pass); // The password is encrypted using md5. $ Query = mysql_query ("select * from user where username = '$ user '"); $ Us = is_array ($ row = mysql_fetch_array ($ query )); $ Ps = $ us? $ Md5pass = $ 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 (); // obtain the logon IP Address $ 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 '] = 'logon failed '; } } Else { $ Arr ['success'] = 0; $ Arr ['msg '] = 'user name or Password error! '; } Echo json_encode ($ arr); // output json data } Elseif ($ action = 'logout') {// exit Unset ($ _ SESSION ); Session_destroy (); Echo '1 '; } |
When the current server exits, you only need to cancel the session and return 1 to the front-end JS for processing. Note that in the above Code, get_client_ip () is a function for obtaining the Client IP address, which is not listed due to space limitations. You can download the source code to view it.
All right, a set of completed user logon and exit procedures are complete, and the shortcomings are inevitable. You are welcome to criticize and correct them.
The above is all the content of this article. I hope you will like it.