Table of Contents
PHP jQuery Ajax implements user login and exit
Home Backend Development PHP Tutorial PHP jQuery Ajax implements user login and logout_PHP tutorial

PHP jQuery Ajax implements user login and logout_PHP tutorial

Jul 13, 2016 am 09:55 AM
ajax jquery php

PHP jQuery Ajax implements user login and exit

 PHP jQuery Ajax implements user login and exit

This article uses Ajax to log in and log out without refreshing, thus improving the user experience. If the user is logged in, the user's relevant login information is displayed, otherwise the login form is displayed.

User login and logout functions are used in many places, and in some projects, we need to use Ajax to log in. After successful login, only part of the page is refreshed, thus improving the user experience. This article will use PHP and jQuery to implement the login and logout functions.

Prepare database

In this example we use 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 '用户名',

`password` varchar(32) NOT NULL COMMENT '密码',

`login_time` int(10) default NULL COMMENT '登录时间',

`login_ip` varchar(32) default NULL COMMENT '登录IP',

`login_counts` int(10) NOT NULL default '0' COMMENT '登录次数',

PRIMARY KEY (`id`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8;

1

2

3

1

2

INSERT INTO `user` (`id`, `username`, `password`, `login_time`, `login_ip`, `login_counts`)

VALUES(1, 'demo', 'fe01ce2a7fbac8fafaed7c982a04e229', '', '', 0);

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 'Login time', `login_ip` varchar(32) default NULL COMMENT 'Login IP', `login_counts` int(10) NOT NULL default '0' COMMENT 'Number of logins', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Then 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 the user enters the user name and password, the user is prompted to log in successfully and displays the relevant login information. If he clicks "Exit", he will exit to the user login interface.

Enter index.php. If the user is logged in, the login information will be displayed. If the user is not logged in, the login box will be displayed to ask the user to log in.

 ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

用户登录

if(isset($_SESSION['user'])){

?>

,恭喜您登录成功!

您这是第次登录本站。

上次登陆本站的时间是:

【退出】

1

2

3

1

2

4

5

6

1

2

3

$(function(){

$("#user").focus();

});

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

User login

<🎜>if(isset($_SESSION['user'])){<🎜> <🎜>?>

, Congratulations on your successful login!

This is the login to this site.

The last time you logged in to this site was:

【Exit】

Note that the statement should be added to the index.php file header: session_start; At the same time, introduce the jquery library in the head part and include global.js. You can also write a beautiful CSS style for the login box. Of course, this example has been slightly written I made a simple style, please check the source code.  ?
1 2
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. As soon as it is opened like Baidu and Google, the mouse cursor will be in the input box. The usage code is as follows:  ?
1 2 3 $(function(){ $("#user").focus(); });

The next thing to do is to present different styles when the input box gains and loses focus. For example, in this example, different border colors are used. 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");

});

1

2

3

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==""){

$('

').html("用户名不能为空!").appendTo('.sub').fadeOut(2000);

$("#user").focus();

return false;

}

if(pass==""){

$('

').html("密码不能为空!").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(){

$('

').addClass("loading").html("正在登录...").css("color","#999")

.appendTo('.sub');

},

success: function(json){

if(json.success==1){

$("#login_form").remove();

var div = "

" json.user ",恭喜您登录成功!

您这是第" json.login_counts "次登录本站。

上次登录本站的时间是:" json.login_time "

【退出】

";

$("#login").append(div);

}else{

$("#msg").remove();

$('

').html(json.msg).css("color","#999").appendTo('.sub')

.fadeOut(2000);

return false;

}

}

});

});

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 login: After the user clicks the login button, it must first verify that the user's input cannot be empty, and then send an Ajax request to the background login.php. When the background verification login is successful, the logged-in user information is returned: such as the number of user logins and the last login time; if the login fails, login failure information is returned.  ?
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==""){ $('
').html("Username 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":pass}, 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!

This is the " json.login_counts " time you have logged into this site.

The last time you logged in to this site was: " json.login_time "

【Exit】

"; $("#login").append(div); }else{ $("#msg").remove(); $('
').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 to get the user information after login, and then append it to the #login element through append to complete. Login operation.

User exit: When "Exit" is clicked, an Ajax request is sent to login.php, all Sessions are logged out in the background, and the page returns to the login interface.

 ?

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 = "

id='pass' />

";

$("#login").append(div);

}

});

});

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 = "

<🎜>id='pass' />

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

login.php

Based on the request submitted by the front desk, when logging in, the user name and password entered by the user are obtained, and compared with the corresponding user name and password in the database. If the comparison is successful, the user's login information will be updated and assembled json data is passed to the front desk.

 ?

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') { //登录

$user = stripslashes(trim($_POST['user']));

$pass = stripslashes(trim($_POST['pass']));

if (emptyempty ($user)) {

echo '用户名不能为空';

exit;

}

if (emptyempty ($pass)) {

echo '密码不能为空';

exit;

}

$md5pass = md5($pass); //密码使用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(); //获取登录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'] = '登录成功!';

$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'] = '登录失败';

}

} else {

$arr['success'] = 0;

$arr['msg'] = '用户名或密码错误!';

}

echo json_encode($arr); //输出json数据

}

elseif ($action == 'logout') { //退出

unset($_SESSION);

session_destroy();

echo '1';

}

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') { //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; } $md5pass = md5($pass); //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(); //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'] = 'Wrong username or password! '; } echo json_encode($arr); //Output json data } elseif ($action == 'logout') { //Exit unset($_SESSION); session_destroy(); echo '1'; }

When the frontend requests to exit, just log out of the session and return 1 to the frontend JS for processing. Note that get_client_ip() in the above code is a function to obtain the client IP. Due to space limitations, it cannot be listed. You can download the source code to view it.

Okay, a complete set of user login and logout procedures is completed. There are inevitable shortcomings. Everyone is welcome to criticize and correct.

The above is the entire content of this article, I hope you all like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/990986.htmlTechArticlePHP jQuery Ajax implements user login and exit PHP jQuery Ajax implements user login and exit This article uses Ajax to log in and exit without refreshing , thereby improving user experience. If the user is logged in...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles