This is a small post for using jQuery AJAX method in PHP to check username availability, I am trying to clear your basic skill to use jQuery AJAX which is being very easy to use everywhere at the present time, while I know there is a lot of articles which had already discussed this topic. But maybe it would be helpful to you.
In this article I created a HTML Textfield and Button, with the jQuery I used “blur” event to passed variable to PHP and retrieve by AJAX and append result into message element. Lets start with the basic HTML.
Start with the HTML Code
<body> <form method="post" name="form1" id="form1" action=""> <div> <label for="username">Username:</label><br /> <input type="text" name="username" id="username" value="" autocomplete="off" /><br /> <div id="message"></div> </div> <div> <input type="button" id="button1" name="button1" value="submit" /> </div> </form> </body>
In the next JavaScript code I used a snippet which I had already discussed in “How to: Create a snippet in Dreamweaver CS5“. Just create a snippet and define a keyboard shortcut. Lets have a look of jQuery skeleton.
jQuery Skeleton
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
});
</script>
Javascript Code
<script type="text/javascript">
$(document).ready(function() {
$("#username").blur(function() { // when focus out
$("#message").html('checking username...'); //before AJAX response
var form_data = {
action: 'check_username',
username: $(this).val()
};
$.ajax({
type: "POST",
url: "functions.php",
data: form_data,
success: function(result) {
$("#message").html(result);
}
});
});
});
</script>
In the jQuery JavaScript I used a file “functions.php” which helps you to give username status either is available or not available. Lets look in next code of functions.php
PHP Code
$action = $_POST['action'];
if($action == 'check_username')
{
$u = $_POST['username'];
_check_username($u);
}
function _check_username($u)
{
$un = array("webwizo", "asif.iqbal", "demo1", "demo2", "demo3");
if(in_array($u, $un))
{
echo "<span class='no'><strong>{$u}</strong> is not available</span>";
}
else
{
echo "<span class='yes'><strong>{$u}</strong> is available</span>";
}
}
Did you see I used in_array method which is most usable in PHP and quite easy. in_array method basically find a string in array and return true | false. You can use by MySQL and stored query result in an Array variable and get true or false status.
If this post doesn’t make you understand, you can view a video tutorial and this video will definitely help you to understand how can you check username availability in PHP.
Thank you!
Popularity: 13%







Comments on this entry (4 comments)
Did you like this post? You can share your opinion with us! Simply click here.