Video icon 64
Learn to Code. Start your free trial today.
Advertisement

Checking Username Availability with Mootools and Request.JSON

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →

This tutorial will teach you how to check username availability with Mootools' Request.JSON and PHP/MySQL

In this tutorial you will learn how to use Mootools' Request.JSON function to check a username against an array or database. In this example we will be using a simple MySQL database. I will try to do as much hand holding as I can, but having a little experience with PHP and MySQL will be a plus.

Tutorial Details

  • PHP Server and MySQL Database required
  • Difficulty: Beginner/Intermediate
  • Estimated Completion Time: 30 - 45 Minutes

Step 1 - The Setup

We are going to create a simple database and add a table. After that we will add a username into the database.

CREATE TABLE IF NOT EXISTS ajax_users (
	id INT(2) NOT NULL PRIMARY KEY AUTO_INCREMENT, 
	user_name VARCHAR(128) NOT NULL
);

INSERT INTO ajax_users VALUES('NULL','matt');

Woohoo, we have a database, a table and a single username. Let's get started with this tutorial!

Step 2 - The Skeleton

preview

For the first step we will create a simple page with one input field for the username and a submit button. Go ahead and open your favorite coding app - mine happens to be Coda - and create a new blank document named index.php. First I'll show you the end result code for this step and then I'll explain it in detail. I find that re-writting the code myself helps it stick, but you can copy and paste if you want.

<!--
	<div id="container">
    
    	<div id="content">
    	
    		<fieldset>

    			<form method="post" action="" id="signup">

    				<ul class="form">
    					<li>
    						<label for="user_name">Username</label>
    						<input type="text" name="user_name" />
    					</li>
    					<li><input type="submit" value="Sign Up Now!" /></li>
    				</ul>
    			
    			</form>
    		
    		</fieldset>
    	
    	</div>
    
    </div>
-->

Now we've got a pretty basic site layout. It will start to come together in step 2 so don't worry if it doesn't really look like much right now.

Step 3 - A little Style

preview

Feel free to style this up however you like, or use the CSS file from the source code.

Step 4 - The Javascript Setup

We are going to need to include the Mootools framework into our php file. Without this, we can't use any of Mootools' classes or functions for our script. There are two ways of doing this. The first way is to use Google's AJAX Libraries API to link to the file. You can view the path Here. The Google libraries give you access to many frameworks so take a look around after you're done the tutorial. To speed things up, we can just use the piece of code below. Place this in your section of your php file.

<script type="text/javacript" src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.3/mootools-yui-compressed.js"></script>

The second way is to head over to the Mootools site

Now that we have the Mootools framework included in our file, we can go ahead and create a new file called main.js, or whatever you want to name it. Once this file has been created lets include it in our php file.

<script type="text/javacript" src="path-to-your-file/main.js"></script>

Go ahead and place that at the bottom of our php file. If you haven't already, let's open up our main.js file.

Step 5 - The Mootools

This part can get a little tricky. Make sure the two files you have open are index.php and main.js as we will be moving back and forth between the files to give you a better idea of how Mootools interacts with the elements in index.php.

The first piece of code we are going to add to main.js tells our Mootools script to execute some code when the DOM has loaded.

	window.addEvent('domready', function() {
		//We are going to fill this with Mootools goodness
	});

Now that the main business is taken care of, we can get our hands dirty.

Step 6 - Adding Events

We need to figure out a way to find out when a user has interacted with our user name input field. We do this using events. Events are Mootools' way of performing some action(s) when a user does something. This can include clicking on a link, pressing down a key, releasing a key, mousing over etc. For this example we are going to fire an event when the user releases a key in the username field.

Before we add the event, we need to give out user name input an ID. Without an ID, Mootools doesn't know which input we are talking about when we tell it to add an event.

Go ahead and add an ID to your user name input in index.php

<input type="text" name="user_name" id="user_name" />

Ok, I swear we will start coding some Mootools right now. Switch back to main.js. Inside your window event, add this code.

$('user_name').addEvent('keyup',function(){
//This is what is fired when the user releases a key inside the username input
}

$('user_name') is what tells Mootools which element we are looking at. It relates to the elements ID.

After that we use .addEvent() to tell Mootools that we want to do something at some point. The first option is the event that we are watching for. We are using keyup. There are tons of other events we can look for. You can read about them at W3C Schools. The last little bit holds a function that we will use to execute some JavaScript code whenever the event is fired.

Step 7 - The Request

Now that we have the event linked up, we can build the request to send when the event is fired. We are going to put this piece of code inside out event.

	...
	The start of our event
	...

    	new Request.JSON({
    		url: "inc/php/json.php", 
    		onSuccess: function(response){
    			
    			
    		}
    	}).get($('signup'));

	...
	The end of our event
	...

Pretty simple looking, eh?! We start off by declaring our request. The first variable is url. This is the path to our PHP that houses our JSON magic. For now, just put in a path to a future file. The second variable is onSuccess. This is a function that is fired if our request is successful. This is where we will put most of our remaining code. Our last little bit, which is easy to look over is the .get($('signup')) variable trailing our request. This takes all our info from our form in index.php and sends it with the JSON request. Without this, the request isn't sending any data, and is pretty much useless. We've now made it useful!

We should probably make our JSON file right now so we don't run into any errors.

Step 8 - The JSON

The concept behind our JSON file is pretty simple in theory. It takes our variables, does whatever we want with it, and then sends it back to our main.js file, all behind the scenes. This is awesome. Take a second to collect yourself.

Ok, now we are all calm, lets create a new file called json.php. If you added the path to your main.js file, name it the same and place it into proper folder. Open this sucker up!

//setup a blank variable
//we will use this as an array to send back
$result = null;

Simple right? The first step is creating a null variable that we will be using as an array later on. Next, we need to connect to our database.

//connect to the mysql database
mysql_connect('localhost', 'root', 'root') or die('Error connecting to mysql');
mysql_select_db('tutorials') or die('Error connecting to table');

We should be all connected. Fill in your database information above. To make sure everything is running smoothly, point to your json.php file. If the page is blank, we are golden. If you see database connection errors, we have a problem. This is usually just a misspelled host/username/password. Double check!

//format the variables
$user_name = mysql_real_escape_string($_GET['user_name']);

//check the database for any users named $user_name
$grab_user = mysql_query("SELECT `user_name` FROM `ajax_users` WHERE `user_name` = '$user_name'");

//check if the query returned anything
if(mysql_num_rows($grab_user) == 0){

	//no user by that name
	$result['action'] = 'success';

}else{

	//oops, already taken
	$result['action'] = 'error';

}

All the variables sent to our json our sent as $_GET. If you've worked with forms before, this shouldn't be anything different. If you haven't worked with PHP forms before, please take a quick look at this page.

We are putting the $_GET variable into a new variable to clean everything up. By wrapping the $_GET variable in the mysql_real_escape_string() function, we are making sure to combat mysql injection. Injection is bad!

Next is the query. We are grabbing any rows from our MySQL database where the user_name row is equal to whatever the user has typed into the user_name input. If the query returns 0, there is no user name match.

If there is no match, we add an action variable to our result array and give it a value of success. If there is a match, we simply give it a value of error.

$result['user_name'] = $_GET['user_name'];

//send the response back
echo json_encode($result);

Finally, we add a user_name variable to the result array and give it a value of our $_GET variable and send it back to main.js using the json_encode() function.

When the JSON is encoded and sent back to the main.js file it looks like the code below

{"action":"success","user_name":"matt"}

That ends the json file, you can save it and close it. You will not need it for this example anymore! Switch back to main.js

Step 9 - Dealing with the Request

We've sent the request, we've checked if the user name exists and we sent the response. So what now? Now we are going to use Mootools to sort through the response and alert the user. How does main.js see what the response is? If we take a quick look back at our onSuccess function, you'll notice that the only variable passed in the function is response. This is the variable that now houses your JSON response. Please add this code inside our onSuccess function.

if(response.action == 'success'){

	//We are good!
    
}else{

    //Username is taken, ouch?!
    alert('Username Taken');

}

We haven't been able to test if our little application is even working right now, so lets take a second to do a quick test. Point your browser to index.php and type matt into your user_name input. Once you are done typing, matt an alert should popup saying Username Taken. You can now delete that alert; it is not needed anymore.

Alerts are boring. They're ugly, they're not very user friendly. Alerts are bad! We need a way to alert the user in a nice, design and user friendly way to alert the user. Open up your style.css and add some styles to your input.

preview
input.success{
	border: 3px solid #9ad81f;
}

input.error{
	border: 3px solid #b92929;
}

We have our styles, and we are receiving a response, lets change the inputs style depending on the response.

$('user_name').removeClass('error');
$('user_name').addClass('success');
preview

We are taking our input and making sure Mootools can find it using $(). After that we add/remove our classes. We make sure to remove the error class incase the script has already added it to our input, then we add the success class. This stops the scripts from adding multiple classes to the input and making it look like input.error.success.error.success. For the response that throws an error, simply reverse the add/remove order.

Give that a test. The input box should have a green outline until you enter in matt as a user name. The input box should then turn red.

That's it. That's the bare bones version of this script. If you want, you can stop reading now and show-off your new tricks to your friends, or you can continue reading. I'm going to expand on the script to make it just a little bit more user friendly.

Step 10 - 1000 Requests

preview

Right now, the script is firing every time a user releases a key. What if you force users to have user names longer than 3 characters. We are basically wasting 3 requests when really, we can just tell the script not to fire unless the input value is more then 3 characters long. This will cut back on the number of requests we are sending to the JSON script!

...
The start of our user name event
...

	var input_value = this.value;
		
	if(input_value.length > 3){

		...
		Request Event
		...

	}

...
The end of our user name event
...

If we wrap our request with the above code, it will only fire the request when the input value is greater than 3. First we put the value into our variable using this.value. this represents our user_name input. Next we check if the length of our value is greater than 3. We do this by using input_value.length. Give it a quick test.

Step 11 - Visuals Please

preview

Remember in our JSON file we were sending our user name value back with our response. This is why. Open up index.php and add a p right underneath our input.

<p id="response"></p>

Now that we have our p with an id of response, we can make Mootools insert some text into it. Open up main.js and place this code inside the onSuccess function.

$('response').set('html','<em>'+response.user_name+'</em> is Available');
preview

Mootools takes $('response') and uses the set() function to insert some text. The first option is what kind of data are we setting. This can either be html or text. Because we are sending an tag are a result, we are using html. We are using response.user_name to grab the user_name variable from our JSON response to keep the user up to date. For the error section, copy over the piece of code and change around the text a little bit to let the user know that the user name is taken.

Step 12 - Submission

Right now, even though we are saying that the user name is taken, the user can still submit the form. This means you would have to use PHP to do another level of error checking. You always want to make sure you are using PHP to make another level of error checking as it is possible for people to get around the disabling of the button. The more layers of security, the better! Open up index.php and find our submit button. Lets disable it!

<input type="submit" value="Sign Up Now!" id="submit_button" disabled="disabled" />
preview

We gave out submit button an id of submit_button so that Mootools can talk to it. Near the close tag we also added disabled. If you point your browser to index.php and try and click on the button, you will notice that nothing will happen. The form has been disabled. Open up main.js

$('submit_button').disabled = false;
preview

If we add that piece of code in our response.success area, it will enable the button. Simply add it to the reponse.error section, change false to true and give it a test. When the user name is available, you should be able to click the button. When taken, the button should be disabled.

Step 13 - The Cleanup

The user has inserted some text, and then deleted all the text from the input. If you notice all the alerts stay on the screen. This is a bit messy. We should probably fix that. Open main.js.

...
The end of our user name event
...

$('user_name').addEvent('blur',function(e){
   
   	if(this.value == ''){
   	
   		$('user_name').removeClass('success');
   		$('user_name').removeClass('error');
   		$('response').set('html','');

   		$('submit_button').disabled = true;
   		
   	}
   
   });

When the user clicks away from the input, it will fire the event blur. If the input box value is empty, we remove all classes, set the response p to empty and disable the button. Nice and tidy!

The End

I hope this tutorial has helped to teach you some of the fundamentals when using simple JSON requests and interacting with elements on the page with Mootools. Feel free to download the source code! If you have any questions, follow me on Twitter!

One last note, the button styles used in this tutorial are the property of Zurb. Check them out, they do great work!


Advertisement