下面是我使用Ajax从数据库检查用户名的代码。来自html页面的输入文本不会转到checkusername.php $_POST['uname'];
可能是什么错误?我尝试了一切仍然无法正常工作。当点击按钮时,用户名文本框中的值如何被带入checkusername.php文件?
html页面代码
<input type="text" name="uname" class="form-control" id="username" placeholder="UserName (0-9,A-Z,a-z)">
<input type='button' id='check_username_availability' value='Check Username Availability'>
<div id='username_availability_result'></div>
checkusername.php
<?php
$con=mysqli_connect("localhost","root","","database")or die(mysqli_error());
//get the username
$username = mysqli_real_escape_string($con,$_POST['uname']);
//mysql query to select field username if it's equal to the username that we check '
$result =mysqli_query($con,"Select username from users where username='$username'") or die(mysqli_error($con));
//if number of rows fields is bigger them 0 that means it's NOT available '
if(mysqli_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
?>
//用于检查实时用户名可用性的脚本
<script>
$(document).ready(function() {
//the min chars for username
var min_chars = 6;
//result texts
var characters_error ='Minimum amount of chars is 6';
var checking_html = 'Checking...';
//when button is clicked
$('#check_username_availability').click(function(){
//run the character number check
if($('#username').val().length < min_chars){
//if it's bellow the minimum show characters_error text '
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
//$('#username_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check username availability
function check_availability(){
//get the username
var username = $('#username').val();
//use ajax to run the check
$.post("checkusername.php",{ username: uname },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_result').html(username + ' is Available');
}else{
//show that the username is NOT available
$('#username_availability_result').html(username + ' is not Available');
}
});
}
</script>
答案 0 :(得分:2)
交换价值:
{ username: uname }
到此:
{ uname: username }
因为当你发送uname
时,php正在期待一个名为$_POST['uname']
的变量username
。
因此,简单的改变是交换对象中的属性。
答案 1 :(得分:1)
简单的拼写错误。
更改
var username = $('#username').val();
//use ajax to run the check
$.post("checkusername.php",{ username: uname },
要
var username = $('#username').val();
//use ajax to run the check
$.post("checkusername.php",{ uname: username },// Observe username.
答案 2 :(得分:0)
您要发布到checkusername.php
{username: uname}
并尝试获取$_POST['uname']
和js中没有uname
变量。
将{ username: uname }
更改为{ uname: username }