Javascript使用实时输出验证PHP上的用户名

I want to use Javascript to validate my input username if it is correct or not showing result on realtime. Here is index.html code:

<html>
<head>
<script>
function showHint(str){
    if(str.length == 0){
        document.getElementById("hint").innerHTML = "";
    }else{
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                document.getElementById("hint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("POST", "demo3.php?input=" + str, true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>

Type a username: <br>
<input id="hint" type="text" name="username" oninput="showHint(this.value)"><p id="hint"></p>

</body>
</html>

Here is the demo3.php code:

<html>
<head>

</head>
<body>
<?php
$mysqli = new mysqli("localhost","root","123456","mini");

$username = $mysqli->real_escape_string($_REQUEST['input']);
$sql = "SELECT username FROM `users` WHERE username='$username'";
    $result = $mysqli->query($sql);
    if($result->num_rows){
        echo "Valid username";
    }else{
        echo "Invalid username";
    }

?>

</body>
</html>

I use the oninput event example from w3cschools, and I am wondering why my result do not show what I expect? And if I assign $username with static variable, demo3.php result seems to be correct feedback, not from index.html.

Plus, I am wondering how to validate multiple forms, such as password and email within the same validation php file. Ex:

input1 -> check username ->output check result
input2-> check password ->output check result
input3-> check email->output check result

New to javascript.All the tutorial seems to provide only one demo, not multiple examples.

查看全部
doujupa7567
doujupa7567
2015/08/31 18:23
  • php
  • javascript
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

2个回复