PHP+Ajax detecting whether the username or email already exists when registering is a common and important function in forums or membership systems. This article briefly describes the implementation method of this function in the form of examples. The specific steps are as follows:
1. PHP detection page
The check.php page code is as follows:
<script type="text/javascript" src="jiance.js"></script> <form name="myform" action="" method="get"> 用户名:<input name="user" value="" type="text" onblur="funtest100()" /> <div id="test100"></div> </form>
2. Ajax verification page
The check.js page code is as follows:
var xmlHttp; function S_xmlhttprequest(){ if(window.ActiveXobject){ xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); }else if(window.XMLHttpRequest){ xmlHttp = new XMLHttpRequest(); } } function funtest100(){ var f = document.getElementsByTagName_r('form')[0].user.value;//获取文本框内容 S_xmlhttprequest(); xmlHttp.open("GET","jcfor.php?id="+f,true);//找开请求 xmlHttp.onreadystatechange = byphp;//准备就绪执行 xmlHttp.send(null);//发送 } function byphp(){ //判断状态 if(xmlHttp.readyState==1){//Ajax状态 document.getElementByIdx_x_x('test100').innerHTML = "正在加载"; } if(xmlHttp.readyState==4){//Ajax状态 if(xmlHttp.status==200){//服务器端状态 var bytest100 = xmlHttp.responseText; //alert(bytest100); document.getElementByIdx_x_x('test100').innerHTML = bytest100; } } }
3. PHP verification page
chkfor.php page code is as follows:
<?php if($_GET[id]){ sleep(1); $conn=mysql_connect('localhost','root',''); mysql_select_db('test',$conn); $sql="SELECT * FROM `user` WHERE `name`='$_GET[id]'"; $q=mysql_query($sql); if(is_array(mysql_fetch_row($q))){ echo "用户名已经存在"; }else{ echo "用户名可以使用"; } } ?>
I hope the examples described in this article will be helpful to everyone in PHP program development.
Files include:
userreg.html (registration page)
ajaxreg .js (AJAX script and real-time verification JS script)
checkuserreg.php (connect to the database and check whether the user name has been Registration page)
userreg.html (Registration page) Copy PHP content to clipboard
PHP code: