PHP + jQuery + Ajax enables user login and exit, jqueryajax

Source: Internet
Author: User
Tags echo date

PHP + jQuery + Ajax enables user login and exit, jqueryajax

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:

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' logon Times ', primary key ('id ')) ENGINE = MyISAM default charset = utf8;

Insert a piece of user information data into the user table:

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.

<Div id = "login"> 

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.

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

$(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:

$("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.

$ (". Btn "). live ('click', function () {var user = $ ("# user "). val (); var pass = $ ("# pass "). val (); if (user = "") {$ ('<div id = "msg"/> 'username .html ("username cannot be blank! "). AppendTo ('. sub '). fadeOut (2000); $ ("# user "). focus (); return false;} if (pass = "") {$ ('<div id = "msg"/> '{.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... ").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> This is the <span> "+ json. login_counts +" </span> logon to this site. </P> <p> the last time you log on to this site is: <span> "+ json. login_time + "</span> </p> <a href = '# 'id = 'logout'> [logout] </a> </p> </ div> "; $ ("# login "). append (div);} else {$ ("# msg "). remove (); $ ('<div id = "errmsg"/> '{.html(json.msg}.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.

$ ("# 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> <label> Password: </label> <input type = 'Password' class = 'input' name = 'pass' id = 'pass'/> </p> <div class = 'sub'> <input type = 'submit 'class = 'btn' value = 'records'/> </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.

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 'user name cannot be blank '; exit;} if (emptyempty ($ pass) {echo 'password cannot be blank'; exit ;} $ md5pass = md5 ($ pass); // use md5 encryption for the password $ query = mysql_query ("select * from user where username = '$ user'"); $ us = I S_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.

Related Article

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