Check username is already exists in database or not using AJAX

This is HTML code for a username textbox

<input name="username" id="username" type="text" class="span12" required onBlur="check_username(this.value);">

Take a div to display an error message like

<div style="display:none; background:#c5c6c9; color:#FFF;" id="error">Username Already Exists!</div>

Now take javascript tag and paste the below function

function check_username(username) {
$.get('ajax/user_modify.php', //give any page which will have a query to check username exists
{username: username},
function(data) {
//alert(data);
if(data==1) {
$('#error').fadeIn(3000);
$('#username').val('');
$('#username').focus();
$('#error').fadeOut(1000);
} else {
$('#error').hide(1000);
}
});
}

The user_modify.php page will have the following PHP code

if(isset($_GET['username'])) {
$username = $_GET['username'];
$select_username = mysql_query("SELECT * FROM tbl_user WHERE username = '$username'");
$result_cnt = mysql_num_rows($select_username);
if($result_cnt>=1){ echo '1';}
else{ echo '0';}
}


The workflow of the above codes is like

1. Enter username and move focus out of the textbox.
2. We called a function on event onBlur of the textbox which will provide the entered value to the function
3. The function then pass the value to the ajax page i.e. user_modify.php
4. On that page, we fire a query that will check if that username is already registered. If yes then echo 1 else echo 0
5. This echoed value will be accepted by the 'data' variable of ajax function
6. Then we will check if it is 1 then show the div which will have an error message else hide it
.....And that's all...




Comments