我正在使用帶有AJAX的基本註冊表單,但表單未連接到數據庫。我顯然忽略了一些東西。檢查用戶名是否可用於AJAX
所以這裏是我想驗證的字段。
Username:<input type="text" name="user" id="user" maxlength="30">
<span id="msgbox" style="display:none"/></input>
然後我使用jQuery,下面的代碼:
$(document).ready(function() {
$("#user").blur(function() {
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
//check the username exists or not from ajax
$.post("user_availability.php",{ user_name:$(this).val() },
function(data) {
if(data=='no') { //if username not avaiable
$("#msgbox").fadeTo(200,0.1,function() {//start fading the messagebox
//add message and change the class of the box and start fading
$(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
});
} else {
$("#msgbox").fadeTo(200,0.1,function() { //start fading the messagebox
//add message and change the class of the box and start fading
$(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);
});
} // else
} // function
); // $.post
}); // blur
}); // ready
而且我有這樣的代碼,user_availability.php
:
mysql_connect(localhost,$user,$password);
or die('There is error to connect to server:-'.mysqli_connect_error());
$db_selected = mysql_select_db($database);
$user_name=$_POST['user_name'];
$sql = "select * from members where username='$user_name'";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
{
$existing_users[] = $row['username'];
}
if (in_array($user_name, $existing_users))
{
echo "no"; //user name is not availble
}
else
{
echo "yes"; //user name is available
}
我沒有得到任何數據庫錯誤。表格將會更加豐富,但我無法使用它來與這個領域合作。有什麼建議麼?
我會從分開解決php頁面本身開始。添加一些代碼來處理$ _GET變量,然後檢查以查看:當它直接訪問它時是否提供了預期的響應? – 2010-08-03 02:22:38
另外,使用Firebug(或類似的工具來檢查請求參數)來驗證你的javascript函數是否將正確的參數傳遞給了php頁面。 – 2010-08-03 02:25:59
嗯...不。問題是這樣的。它沒有連接到數據庫。 我的意思是,當一個新用戶輸入他的用戶名,並且它已經在數據庫中。它仍然說'用戶名可用'..但事實是它不可用。 – mayumi 2010-08-03 02:27:31