[PHP][Ajax][Javascript]Username checking

Post all your tuts or request for tuts here.
Post Reply
User avatar
Chris
Posts: 1581
Joined: Wed Sep 30, 2009 7:22 pm

[PHP][Ajax][Javascript]Username checking

Post by Chris »

I noticed there was a request for it. So I'll make it :D. I know this is my 3rd tutorial in 2 days but I'm bored.

Step 1. Writing our xHTML.
We will make a xHTML page first with a text field inside it.
in our input tag for the username we will call a javascript function called "checkUsername()" onkeyup.

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Username Checker Tutorial</title>
	</head>

	<body>
		Username
		<input type="text" name="username" id="username" onkeyup="checkUsername();" />
	</body>
	
</html>
Step 2. Javascript and Ajax
Okay, first we make a function that starts a new Ajax object, because some browsers don't support XMLHttpRequest(); we call it as an ActiveXObject (for IE)
XMLHttpRequest(); is the Ajax class, it contains all the methods and attributes that Ajax uses.

<script type="text/javascript">
function getAjax()
{
    var ajax = null;
    try 
    {
        ajax = new XMLHttpRequest();
    }
    catch(e)
    {
        //IE support
        try
        {
            ajax = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            try 
            {
                ajax = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e) {}
        }
    }
    return  ajax;
}
</script>

If we need to start a new ajax object all we need to do is set a variable to getAjax();
var ajax = getAjax();
with our ajax variable which now holds the ajax class, we can call some ajax methods and attributes.

Opening a page
to open a page with ajax we call the open() method. ajax.open(method, url, async)

The method, GET or POST.
the url of the page that will be fetched.
async is a boolean, true(asynchronous) or false(synchronous).

if we set the method to POST we can send some parameters through the send() method, but this also requires some extra headers to be sent.
To keep it simple I'll show you with the GET method
this will be what our method will look like:

ajax.open("GET""checkusername.php?username="true);

this will open checkusername.php. We will also need to send some parameters so the PHP can read what the username that has been entered is.
to do this we use some javascript to get the value of the username field.

var username = document.getElementById("username");

with the we can then get the value of the username field using the .value attribue:

username.value

so in the end our open method should look like this:

ajax.open("GET""checkusername.php?username="+username.value, true);

because we won't be sending any post parameters the send method in ajax doesn't have to be set. But it does need to be called.
This can be done after the open method.

ajax.send(null);

because when you visit a web page. it doesn't load straight away, we need to check what state the page is in. Is it loading? Has it been loaded. If it's been loaded the readyState attribute in ajax will be 4.
But it won't be 4 straight away, thats why there is another ajax attribute called onreadystatechange. We can use onreadystatechange to call a funtion, which will then check what state readyState it in:

ajax.onreadystatechange = function()
{
   if( ajax.readyState == 4 )
   {
      //The page has loaded we can now check what its contents are.
   }
}

The pages contents are stored in the responseText attribute. We can then check what the contents of the page are with an if.
if( ajax.readyState == 4 )
{
    if( ajax.responseText == "1" )
    {
        username.style.border = '#F00 1px solid';
    }
    //The username isn't use
    if( ajax.responseText == "0" )
    {
        username.style.border = '#0F0 1px solid';
    }
}


Here's the whole script put together.
<script type="text/javascript">
function getAjax()
{
    var ajax = null;
    try 
    {
        ajax = new XMLHttpRequest();
    }
    catch(e)
    {
        //IE support
        try
        {
            ajax = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            try 
            {
                ajax = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e) {}
        }
    }
    return  ajax;
}
//function called when the username field is changed
function checkUsername()
{
   //Start a new ajax object.
   var ajax = getAjax();
   //Check if it was possible
   if( ajax != null )
   {
      //Ajax is supported, we can now call different functions from the ajax class.
      
      //Get the username field into a variable
      var username = document.getElementById("username");
      
      //Requesting the PHP script that checks the username. checkusername.php
      ajax.open("GET""checkusername.php?username="+username.value, true);
      
      //Call a function when the state changes. The state will change if the page is loading or has been loaded.
      ajax.onreadystatechange = function()
      {
         //If the page we are trying to get hasn't loaded yet make the border orange..
         if( ajax.readyState != 4 )
         {
            username.style.border = '#F90 1px solid';
         }
         
         //If the page has loaded, we can check what the response was from the page
         if( ajax.readyState == 4 )
         {
            if( ajax.responseText == "1" )
            {
               username.style.border = '#F00 1px solid';
            }
            //The username isn't use
            if( ajax.responseText == "0" )
            {
               username.style.border = '#0F0 1px solid';
            }
         }
      }
      ajax.send(null);
   }
   else
   {
      //Ajax was not supported by the browser
      alert("Ajax not supported");
   }
}
</script>

Step 3. The PHP script. I'm going to keep this simple and just set a vairable and an if.
If the username you enter is username. The border of the box will turn red.
save this as checkusername.php

Code: Select all

<?php

//Check the username
if( empty($_GET['username']) === false )
{
    if( $_GET['username'] == 'username' )
    {
        echo "1";
    }
    else
    {
        echo "0";
    }
}
else
{
    echo "0";
}
?>
Well that is it. Script done. You can use this method to do lots of things. I hope this helps.
Doesnt matter what this one is saved as

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Username Checker Tutorial</title>
		<script type="text/javascript">
		function getAjax()
		{
			var ajax = null;
			try
			{
				ajax = new XMLHttpRequest();
			}
			catch(e)
			{
				//IE support
				try
				{
					ajax = new ActiveXObject("Msxml2.XMLHTTP");
				}
				catch(e)
				{
					try
					{
						ajax = new ActiveXObject("Microsoft.XMLHTTP");
					}
					catch(e) {}
				}
			}
			return ajax;
		}
		
		//function called when the username field is changed
		function checkUsername()
		{
			//Start a new ajax object.
			var ajax = getAjax();
			//Check if it was possible
			if( ajax != null )
			{
				//Ajax is supported, we can now call different functions from the ajax class.
				
				//Get the username field into a variable
				var username = document.getElementById("username");
				
				//Requesting the PHP script that checks the username. checkusername.php
				ajax.open("GET", "checkusername.php?username="+username.value, true);
				
				//Call a function when the state changes. The state will change if the page is loading or has been loaded.
				ajax.onreadystatechange = function()
				{
		
					//If the page we are trying to get hasn't loaded yet make the border orange..
					if( ajax.readyState != 4 )
					{
						username.style.border = '#F90 1px solid';
					}
					
					//If the page has loaded, we can check what the response was from the page
					if( ajax.readyState == 4 )
					{
						if( ajax.responseText == "1" )
						{
							username.style.border = '#F00 1px solid';
						}
						//The username isn't use
						if( ajax.responseText == "0" )
						{
							username.style.border = '#0F0 1px solid';
						}
					}
				}
				ajax.send(null);

			}
			else
			{
				//Ajax was not supported by the browser
				alert("Ajax not supported");
			}
		}
		</script>
	</head>

	<body>
		Username
		<input type="text" name="username" id="username" onkeyup="checkUsername();" />
	</body>
	
</html>
Here are the script put togehter.
checkusername.php

Code: Select all

<?php

//Check the username
if( empty($_GET['username']) === false )
{
    if( $_GET['username'] == 'username' )
    {
        echo "1";
    }
    else
    {
        echo "0";
    }
}
else
{
    echo "0";
}
?>
Last edited by Chris on Thu Dec 24, 2009 2:53 pm, edited 3 times in total.
Fighting for peace is declaring war on war. If you want peace be peaceful.
User avatar
Torniquet
Posts: 869
Joined: Sun Aug 02, 2009 6:18 am

Re: [PHP][Ajax][Javascript]Username checking

Post by Torniquet »

n1 (y)

any chance you can give a proper run through of what each componant of the ajax does?? i hate the whole copy paste thing without knowin wht things are doing (which is why i generally dont learn from written tuts lol)

thnx :)
New Site Coming Soon! Stay tuned :D
User avatar
Chris
Posts: 1581
Joined: Wed Sep 30, 2009 7:22 pm

Re: [PHP][Ajax][Javascript]Username checking

Post by Chris »

I updated it a bit, and put colours on the javascript to make it easier to read. Hope that helps.
Fighting for peace is declaring war on war. If you want peace be peaceful.
User avatar
Torniquet
Posts: 869
Joined: Sun Aug 02, 2009 6:18 am

Re: [PHP][Ajax][Javascript]Username checking

Post by Torniquet »

yeah thats awsome thanks :)

just one question tho :D lol

where does it check to see if the username is taken?? or is that something that needs to be added after the

if( empty($_GET['username']) === false )
{

statement in the php script? then alter the next if statement?
New Site Coming Soon! Stay tuned :D
User avatar
Chris
Posts: 1581
Joined: Wed Sep 30, 2009 7:22 pm

Re: [PHP][Ajax][Javascript]Username checking

Post by Chris »

I was half expecting that question :P But didn't want to spoon feed to much.

First it checks if $_GET['username'] is set, so we won't get a PHP error. That's the
if( empty($_GET['username']) === false )

Then it checks what the username is if it is set
if( $_GET['username'] == 'username' )
{
    echo "1";
}
else
{
    echo "0";
}

So if the username you typed in was "username" you will get a red border. If it isn't username you wont.

I'm guessing you want to check wether it already exists in the database. Here's what the php would look like:

Code: Select all

<?php
//Check the username
if( empty($_GET['username']) === false )
{
    $query = mysql_query("SELECT * FROM `users_table` WHERE `username` = '". addslashes(htmlentites($_GET['username'])) ."'");
    if( mysql_num_rows($query) != 0 )
    {
        echo "1";
    }
    else
    {
        echo "0";
    }
}
else
{
    echo "0";
}
?>
Fighting for peace is declaring war on war. If you want peace be peaceful.
User avatar
Torniquet
Posts: 869
Joined: Sun Aug 02, 2009 6:18 am

Re: [PHP][Ajax][Javascript]Username checking

Post by Torniquet »

ye thought as much :)

ta alot chris. can change the crap i got goin on in my site now lol ^^
New Site Coming Soon! Stay tuned :D
Post Reply

Return to “Tutorials”