search
HomeBackend DevelopmentPHP TutorialThinkphp+AJAX dynamically verifies whether user input is legal_PHP tutorial

When encountering user registration and other situations, if you wait for the user to enter all the information, click the registration button to submit, and then verify whether the input is correct, the experience will be very bad, it will waste the user's time and increase the registration cost. Here is an example , demonstrates how to use ajax for single-step verification, using thinkphp 3.2 framework, environment WAMPServer 2.4, version PHP 5.4.16+ Apache 2.4.4+ MySql 5.6.12

1. Database design:

Database name thinkphp

Table name tp_user where tp_ is the table prefix, which can be defined in config.php. When operating the table, just use user

CREATE TABLE IF NOT EXISTS `tp_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

2. Page design

3. HTML part

view/Index/index.html




4. thinkphp automatic verification

protected $_validate=array(
		array('username','require','用户名不能为空!'),
		array('username','','用户名已经存在',0,'unique',1), 
		array('username','/^[a-zA-Z][a-zA-Z0-9_]{1,19}$/','用户名不合法!'),	
			
		array('email','require','邮箱不能为空!'),
		array('email','email','邮箱格式不正确!'),
		array('email','','该邮箱已经注册过!',0,'unique',1),
	);
	
	protected $_auto = array( 
		array('password', 'md5', 1, 'function'), // 对password字段在新增的时候使md5函数处理
	);

5. Use ajax

After the user enters the username, the blur event will be triggered when the input box loses focus. You can verify whether the username input is correct at this time

jQuery.post( url, [data], [callback], [type] ): Use POST method to make asynchronous requests

Parameters:

url (String): URL address to send the request.

data (Map): (optional) The data to be sent to the server, expressed in the form of key-value pairs of Keyalue.

callback (Function): (optional) Callback function when loading is successful (this method is called only when the return status of Response is success).

type (String): (optional) The official description is: Type of data to be sent. In fact, it should be the type requested by the client (JSON, XML, etc.)

$('#username').blur(
			function() {
				var username = $(this).val();
				$.post(index.php/Home/Index/checkName, {
					'username' : username//前一个username需要跟UserModel对应,即跟数据库字段对应
				}, function(data) {
					if (data == 0) {
						error['username'] = 0;
						$('#tooltip1').attr('class',
								'tooltip-info visible-inline success');
					} else {
						error['username'] = 1;
						$('#tooltip1').attr('class',
								'tooltip-info visible-inline error');
						$('#mess1').html(data);
					}
				})
				return false;
			});

Password, repeat password, email verification are similar

You need to pay attention when verifying the email. If the user clicks the registration button immediately after entering the email, the click event of the registration button and the blur event of the email input box will be executed at the same time. Since the email verification is $.post, it is asynchronous. The post has not been executed yet, error['email']=1 in the click event, $('#submit1').submit(); will not be executed, so at this time, set a flag error['submit'] = 0;0 Indicates that the registration button has been clicked. The default is 1. In the email blur callback function, it is judged whether error['submit'] is equal to 0, that is, whether it has been clicked. If it has been clicked, the form is submitted. If not, only the email needs to be verified.

After the user enters the email address and clicks the mouse elsewhere on the screen, only blur will be executed, the same as the username and password.

6. Server processing

public function checkName() {
		$user = D ( 'user' );
		if (! $user->create ()) {
			exit ( $user->getError () );
		} else {
			echo 0;//这是回传给$.post的数据,对应上面的data
		}
	}

The above is the method of single-step verification of user name. Let’s see how to submit all data to the server

7. Submit all data to the server

Through the above html code, I noticed that a form is used here, the form is submitted in post mode, and the action points to the address that the server can handle
When clicking the registration button, first determine whether all inputs are correct. If correct, submit the form

$('#submit1').click(function() {
		if ($('#username').val() == '') {
			$('#tooltip1').attr('class', 'tooltip-info visible-inline error');
			$('#mess1').html(用户名不能为空!);
		}
		if ($('#password').val() == '') {
			$('#tooltip2').attr('class', 'tooltip-info visible-inline error');
			$('#mess2').html(密码不能为空!);
		}
		if ($('#repassword').val() == '') {
			$('#tooltip22').attr('class', 'tooltip-info visible-inline error');
			$('#mess22').html(确认密码不能为空!);
		}
		if ($('#email').val() == '') {
			$('#tooltip3').attr('class', 'tooltip-info visible-inline error');
			$('#mess3').html(邮箱不能为空!);
		}
		if (error['username'] == 1) {
			var scroll_offset = $(#tooltip1).offset(); // 如果用户名验证失败,屏幕会滚动到用户名的位置,让用户重新输入
			$(body,html).animate({
				scrollTop : scroll_offset.top
			// 让body的scrollTop等于pos的top,就实现了滚动
			}, 0);
			return false;
		} else if (error['password'] == 1) {

			return false;
		} else if (error['email'] == 1) {
			error['submit'] = 0;
			return true;
		} else {			
			$('#submit1').submit();
			return true;
		}
	});

The server-side register method receives all data. If successful, it will jump to the Home/index page. If it fails, it will jump to the error page.

public function register() {
		$user = D ( 'user' );
		if (! $user->create ()) {
			dump ( $user->getError () );
		}
		$uid = $user->add ();
		
		if ($uid) {
			$_SESSION ['username'] = $_POST ['username'];
			$this->redirect ( 'Home/index' );
		} else {
			$this->error ( 注册失败! );
		}
	}

8. config.php configuration

<!--?php
return array(
	 /* 数据库配置 */
    &#39;DB_TYPE&#39;   =--> &#39;mysql&#39;, // 数据库类型
    &#39;DB_HOST&#39;   => &#39;127.0.0.1&#39;, // 服务器地址
    &#39;DB_NAME&#39;   => &#39;thinkphp&#39;, // 数据库名
    &#39;DB_USER&#39;   => &#39;root&#39;, // 用户名
    &#39;DB_PWD&#39;    => &#39;123&#39;,  // 密码
    &#39;DB_PORT&#39;   => &#39;3306&#39;, // 端口
    &#39;DB_PREFIX&#39; => &#39;tp_&#39;, // 数据库表前缀
);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/929774.htmlTechArticleThinkphp+AJAX dynamically verifies whether the user input is legal. When encountering user registration and other situations, if you wait for the user to enter all information, After clicking the registration button to submit, verify that the input is correct, body...
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment