Try Tuts+ Premium, Get Cash Back!
Checking User Name availability using Mootools and Request.JSON

Checking Username Availability with Mootools and Request.JSON

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">

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">

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!


Tags: MooTools
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • sam

    I will read it later on thanx for posting.

    • jaded

      Why do people like you post? You have nothing to contribute. It’s almost as annoying as those people that post ‘first!’. Who cares?

      • Jerre

        I’ll read your comment later on, thanx for replying.

      • http://www.themerchantofvenice.com.au/ Josh

        I concur with jaded.
        Still amazes me that after tuts about a better web there still isnt a “thanks” button.
        Envato must be very rich to use (waste) all this bandwidth for completely useless and unconstructive posts with literally nothing useful or worth reading, and the article popularity can be checked with a thanks button.
        Oh, and hey, Great post, thanks!

      • http://www.twitter.com/omfg_followme John

        “Why do people like you post? You have nothing to contribute. It’s almost as annoying as those people that post ‘first!’. Who cares?” Haha… because it is another way of saying, “I’m a spam bot who puts this same generic comment on all blogs… but sometimes it is easier to get away with it like this” :)

        Meeee, cynical? HELL YES.

  • http://www.philohermans.com Philo

    Did a quick look, looks great! Will try it out later on!

  • http://twitter.com/dwpers Dan

    This is a great tutorial. Thank you :)

  • http://blog.piotrnalepa.pl Sun Pietro

    well, it’s extremely useful thing to know :)

  • http://firs.org.ua Firs Yura

    A good lesson for the novice programmer! Thank you! I’ll wait for the next more complex lessons!

    • http://envexlabs.com Matt Vickers
      Author

      Is there any specific area you’re looking to have covered?

  • http://www.fatlizardmedia.com Juan C Rois

    Very nice tut, I actually need to implement this for a website that I’m working on.
    I’m going to try to duplicate this using jQuery but I just have a quick question.

    Matt, do you think it is possible to get raw data from the database instead of a JSON set of records? just curious.
    Thanks a lot for this article, very well written.

    • http://www.envexlabs.com Matt Vickers
      Author

      @juan: send me a DM on twitter (@envex) and we can toss some ideas back and forth, i just don’t like i’m understanding the question properly.

  • http://kolophon.net Jacob Harvey

    I had someone pass along a script (for livesearch) that basically stopped at your Step 10 a while back. Along with the character limit I also put in a timer to delay the submission briefly. People type pretty fast and that short delay keeps things local, sometimes only polling the backend once or twice instead of seven times (with the three character limit example) for a ten character term.

  • http://www.mshelp.be Sven Vanoirbeek

    Thanks for the tutorial
    just read & tested it and looks really nice.
    I also like the css work..

  • http://www.sorinistudor.ro Sorin Istudor

    Thanks for the tutorial. There aren’t so many tutorials with mootools platform on nettuts, like jquery. Maybe Jeffry can start an screencast about that, it wood be awsome.

    • http://envexlabs.com Matt Vickers
      Author

      I’ve recorded a few beginner mootools screencasts for the NetTuts screenr competition.

      Feel free to check them out: http://screenr.com/user/envex

      I feel kinda dirty about that plug, but i’m going to leave it :D

  • elkaz

    Bring back raw js.

    • http://spotdex.com David Moreen

      No one uses that stuff anymore.

  • jQuery Lover

    noo….no raw js and no moo shit tools -> jQuery

  • http://www.newadvertise.com Karim

    just what i was looking for :-) i’ll be using it in the website am developing now
    Thanks a bunch for the post

  • http://myfacefriends.com Myfacefriends

    very good indeed! thanks for the tuts!

  • http://tutorialblog.info/ tutorial blog

    Good tutorial. Thank your share..

  • leo rapirap

    you made it look very simple.
    i tried it and happy with the result and will definitely used it in
    my future projects.

  • http://www.webdevebooks.com webdevebooks

    Very nice luv it !!

  • http://www.tutdepot.com Martyn

    Great tutorial, I’ve never used Mootools i’ve always been a JQuery person but it looks very nice!

  • Matt

    You suggest using JavaScript to block the submission of the form if the user name is taken/not entered/not long enough, in lieu of doing the check on the server. While this is certainly a great way to prevent a normal user from accidentally clicking through the form, I would not rely on a client-side script to do anything validation-wise. Any one who knows JavaScript could easily bypass your check and submit his or her form to the server, and get whatever user name they wanted, regardless of whether it meets your requirements or not. Other than that, I think it’s a good tutorial.

    • http://spotdex.com David Moreen

      True that, but everyone knows, that you use javascript for the connivence of everything. You always have server-side validation as a back up. ;D

  • http://www.jeffadams.co.uk Jeff Adams

    Oh I love it! I’m more a jQuery guy but it’s always nice to be exposed to Mootools as well – thanks a bunch. In fact might even take another look at Moo Tools now.

    I just read the comment above as I was typing – how ironic that I said pretty much the same thing lol.

    Keep up the awesome tutorials.

  • http://www.yourflighttimes.com/ James

    Thanks! Nice tut loving the style!

  • http://www.ebuyukkaya.net Ekrem Büyükkaya

    As a jQuery person, I liked it but I think I must see more good tutorials about mootools to begin using =)

  • Neil

    Nice article, not sure about returning JSON though.

    • http://envexlabs.com Matt Vickers
      Author

      Hey,

      What method would you use?

      I’m always looking for suggestions on the most efficient methods.

  • http://www.eddiemonge.com Eddie Monge

    In step 12, you say that the extra PHP validation isn’t necessary. I strongly disagree. You should still have the PHP validation in there. You never know what a user will do and having validation on the front and back ends is not only a smart thing to do, but should be a requirement. Anyone could always change what is sent with something as simple as Firebug and get around the system.

    I also agree with the comment above from Jacob Harvey in the fact that people do type fast and maybe an advanced version of this tutorial should be made that only fires when the person has stopped typing for a few hundred millisecond. Not enough to be a really big delay, but enough so that there isnt really a million requests sent to the server. That could kill a server if your app gets picked up by a big blog and people flock to register on it.

    • http://envexlabs.com Matt Vickers
      Author

      You are correct,

      As I said below, I guess I was just trying to focus on the Mootools aspects and overlooked the PHP validation.

      I’ve made an edit to the article.

  • http://UrbanRiver.com Rafal

    Very cool post. Could you duplicate this in JQuery??

  • http://www.d-lists.co.uk AtiKuSDesign

    I don’t really use mootools but I’m liking it’s use here.

    Thanks for sharing

  • http://www.indev.nl Matthijn Dijkstra

    It seems you say something like this:

    ‘No need for checking in PHP with the submit, since when Javascript is disabled, the button is disabled as wel…. but a user can (with some browser plugins) enable the button even if Javascript is not turned on. For example, Firefox with Firebug/Webdeveloppers toolbar could do that, and Safari can do it out of the box (if the Developers menu is turned on).

    So, it comes down to. Always check serverside as wel.

    • http://envexlabs.com Matt Vickers
      Author

      Hey,

      You are correct. I always check variables server side as well, but I guess I was more concerned with focusing on Mootools instead of running the user through a validation lesson. I will remember for next time!

      Thanks.

  • http://www.sergiomasellis.com Sergio Masellis

    question isn’t this:

    supposed to be:

    maybe it doesn’t matter just wondering.

  • http://www.freshclickmedia.com Shane

    That was a nice in-depth tutorial.

    My only comment would be that since server-side is effectively returning either a ‘yes’ or a ‘no’, a Boolean return type would be more appropriate for a number of reasons.

  • Nate

    Not a bad tutorial. Quick pointer for anyone trying to implement this.

    In step 10 the author mentions the possibility for too much data being sent. This can easily be solved by using the more logical option blur for binding the name check.
    Now you are probably saying “that is stupid” the user could just click out of the field and onto the submit button right away and then the check is worthless. This is why you also implement a second check in the submit button to see if the username check completed successfully. Furthermore if the user clicks submit you fire the username check if it hasn’t been and make a function call back to the form submit.

    I’m thinking about submitting a jQuery tutorial version of this since I just recently completed this logic for a recent client project. I will if I have time to write it up :)

  • jem

    Nice tut.

    Good to see some Mootools! Though this tutorial doesn’t really explore its depths, I’ve always found it a stronger/more complete framework for working with bigger js projects.

    I think clientside validation (through javascript) should always be more of an enhancement.

    You could just as easily build logic into the page code to check if the AJAX request headers are present from an AXJAX form submit… if so perform the typical PHP validation but return the validation in a js friendly manner (perhaps in the form of JSON again) to let you know which fields are correct/incorrect… and if fields were all correct, the PHP can silently commit that information to the database.

    This way, nobody can ever spoof your validation using their own JS, and the user experience is as pleasant as possible. Plus, the page would work for people with or without js.

  • http://www.lincoln-plumbing.co.uk/ Lincoln Plumber

    Brilliant – I have been looking for a tutorial like this for days. I need it for a gallery I’m setting up where visitors have the chance to upload their holiday snaps.

    Thanks for sharing!!

  • http://ibuildstuff.net Damian Dawber

    Someone noted above they would like to see more complex examples. Unfortunately, they didn’t give any example of what exactly they would like to see, so here’s a (possibly bland) suggestion:

    Since everyone really loves jQuery these days, let’s push MooTools on the basis that it actually FEELS like you’re writing JavaScript. Such concepts as modifying prototypes and using the Class function as an inheritance pattern are something I came across that might well be interesting… certainly would please moi :)

  • http://www.xmentoys.net X Men Toys

    This is a excellent feature to have on forms. I think it helps the website owner, because it makes it easier for subscribers to sign up without getting frustrated when finding out the username has been taken after clicking the submit button. Real time saver! Thanks for the tutorial

  • Mick

    Thanks, very useful and works great.

  • http://www.southeasttexas.com Billy R Baldwin

    Very useful and informative tutorial sir.

  • http://www.baipou.com chinese

    Nice!
    Thanks!

  • Mr.Code

    Wow! Thank you for the help. Noobie coder here, this helps a lot. Thanks again.

  • samir

    Very Gud Article

    But how do same for asp.net??

    Waiting for Your Kind Reply…

    reagards,
    Samir