Checking username availability from the database using ajax

Posted in: javascript by musiitwa joseph 2015-11-03 at 05:54:38

image for Checking username availability from the database using ajax After filling in the username, the javascript onblur event calls the function check_username(), which sends an ajax PoST request to usernames.php. Username.php has a connection to the database which checks if there is a match with database stored usernames. The status is updated in the div with aclass status(div class="status")
<form class="form" action="" method="post">		
	<div class="form_title">Registration form</div>
<input type="text" value="" name="" placeholder="First name"/><br />
<input type="text" value="" name="" placeholder="Last name"/><br />
<input type="text" value="" name="" id="uname" placeholder="Username" onBlur="return check_username();"/> <div id="status"><!-- availability of the username message is inserted into this div--></div>
<input type="password" value="" name="" placeholder="Password"/><br />
<input type="submit" value="Submit">&nbsp;&nbsp;<input type="reset" value="Cancel"> </form> <script type="text/javascript" src="javascript.js"></script>


function _(x){
	return document.getElementById(x);
function check_username(){
	var u_name = _("uname").value;
	var status = _("status");				
	if(u_name == "") return false;
	status.innerHTML = 'loading...';//shows before or while match for username is taking place 
	var request = new XMLHttpRequest();"POST", "usernames.php", true);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");			
	request.onreadystatechange = function() {
		if(request.readyState == 4 && request.status == 200) {
			//4    = The connection is complete, the data was sent or retrieved.
			//200  = The file has been retrieved and you are free to do something with it
			status.innerHTML = request.responseText;



$uname = $_POST['uname'];

$connect = mysqli_connect("localhost","codeeagl_see","demo123!","codeeagl_demo");

$select = mysqli_query($connect, "select user_username from users where user_username = '$uname'");

if(mysqli_num_rows($select) == 0)
	echo '<span class="success">Username is Available</span>';
	echo '<span class="error">Username already taken</span>';