[英]AJAX Username check not validating
PHP / MySQL的。 我創建了一個包含用戶名文本字段和按鈕的簡單表單。 頁面名稱是checkusername.php 。 我也寫了一個AJAX函數。 然后,我還有另一個頁面usercheckpage.php ,其中checkusername.php中的值是通過AJAX函數getResult()
傳遞的。
在usercheckpage.php中 ,在數據庫表中檢查用戶名(如果已經存在),則顯示'username not available'
,如果可用,則顯示'username available'
。
但是問題是,即使顯示警告消息'username not available'
,如果我單擊提交按鈕,該值也會傳遞到我的下一頁insertusername.php中 。 如果用戶名不可用,我不希望表單被提交。 我嘗試了html5驗證。 但是效果不是很好。
這是我的代碼:
checkusername.php
<form id="form1" name="form1" method="post" action="../controller/insertusername.php">
label for="txtuname"></label>
<input type="text" name="txtuname" id="txtuname" required onblur="getResult(this.value);" />
<span id="showusername"></span>
<input type="submit" name="submit" id="submit" value="SUBMIT" />
</form>
AjAX功能
function getResult(uname)
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()//callback fn
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('showusername').innerHTML=xmlhttp.responseText;
}
xmlhttp.open("GET","checkusername.php?variable="+uname,true);
xmlhttp.send();
}
checkusername.php
<?php
include '../model/Query.php';
$un=$_GET["variable"];
$name="select username from login where username='".$un."'";
$res=getData($name);
while($row=mysqli_fetch_array($res))
{
$name1=$row["username"];
}
if($un==$name1)
{
echo "name already exist";
}
else
{
echo "ok";
}
?>
HTML
添加提交事件
<form id="form1" name="form1" method="post" action="../controller/insertusername.php" onsubmit="checkUsername()">
AJAX
編輯您的getResult函數以返回true
或false
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById('showusername').innerHTML=xmlhttp.responseText;
return (xmlhttp.responseText == 'ok') true : false;
}
然后創建一個非常簡單的函數, onsubmit
檢查用戶名是否可用。 如果不是,則返回false
並且不會提交該表單。
function checkUsername(){
var username = document.getElementById("txtuname").value;
if(!getResult(username))
return false;
}
希望這可以幫助 :-)
要使其正常工作,請將按鈕更改為
<input type="button" value="Submit" onclick="check()">
並添加方法
function check(){
if(getElementById('showusername').innerHTML=="ok"){
document.getElementById("form1").submit();
}
}
我希望它能起作用...
HTML
添加提交事件
<form id="form1" name="form1" method="post" action="../controller/insertusername.php" onsubmit="checkUsername()">
AJAX
編輯您的getResult函數以返回true或false
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById('showusername').innerHTML=xmlhttp.responseText;
return (xmlhttp.responseText == 'ok') true : false;
}
然后創建一個非常簡單的函數,onsubmit會檢查用戶名是否可用。 如果不是,則返回false,並且不會提交該表單。
function checkUsername(){
var username = document.getElementById("txtuname").value;
if(!getResult(username))
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.