Wednesday, October 5, 2011

AJAX Using JQuery and PHP to Check Availability of User Name

Again, I compiled these codes from several sources and it's hard to give credit to all of them as some of them I only use several lines and some I only use the concept. Many I found are not fully working. That's why I want to show you the one that's working for me (I'm using PHP5 with Windows 7 via IIS7).

Note: Especially the part JQUERY AJAX pass JSON data to PHP. I don't need to decode the data in PHP. If json_decode() is used, the data will be gone. I really don't know why most examples are decoding the JSON data. But the return of JSON to JQUERY requires the json_encode() to do the job.



The JQUERY CODES:


$(document).ready(function()
{
$("#checkName").click(function(e)
{
userName = $(document.myForm.username).val();

if(userName.length <= 3)
{
$("#display").text("username must be at least 4 characters");
$("#display").css("color","red");
$("#display").css("font-size","11");
}

else
{
$.ajax(
{
type: 'POST',
url: 'CheckUserName.php',
data: {
userName: $(document.myForm.username).val()
},
dataType: 'json',
success: function(response)
{
if(response.found == false)
{
$("#display").text("username is available");
$("#display").css("background-color","lightgreen");
}
else
{
$("#display").text("username is already taken");
$("#display").css("background-color","red");
}
}
});
}
});
});





The HTML:


<form name=myForm>

<input type=text name=username size=35 maxlength=200>

<input type=button name=checkName id=checkName value="Check Availability">

<div id="display"></div>

</form>





The PHP (CheckUserName.php) :


<?PHP

$username = $_POST['userName']; // no need to decode JSON

$dblink = mysql_connect(yourhost, 'yourID', 'yourPassword');

if (!$dblink) {
die('Could not connect: ' . mysql_error());
}

mysql_select_db('yourDBname');

$result = mysql_query("select * from yourMemberNamelist where Username = '$username'");

while ($row = mysql_fetch_assoc($result)) {
$temp = $row["Username"];

}


if ($temp != $_POST['userName']) {
$return['found'] = false;
}
else {
$return['found'] = true;
}

echo json_encode($return);


return;

?>




Again, I put those highlights in red to signify "attention". This is what works for me using IIS7. I'm not sure why there are so many codes out there that is not really working. Maybe it's my IIS7 with PHP5.

No comments:

Post a Comment