Hello, in this tutorial you will learn how to create a live user validation, where it checks the database for existing users, and reports out whether it is taken or not using live ajax. This can be applied for many other similar techniques, such as live validation, live email validation e.t.c.
For this tutorial, you will need a mysql database, and a server with PHP Installed. If you do not currently own a server, or have hosting with PHP enabled then please download PHP here.
Step 1) Creating the index.html file
This file will be the easiest file in this tutorial. All it is is a simple html page with a form added. I have applied some simple styles to the page to make it look a bit nicer, but you can take those off if you wish. This file will hold all of the scripts, brining them together. Without this file, the script would not work.
Create a new file called ‘index.html’ (without the quotes) and save it. Insert this bit of code (Below) into the index.html file and then save it again.
<html>
<head>
<style type="text/css">
.correct
{
color:#B3DF00;
}
.wrong
{
color:#FF0000;
}
body,td,th {
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
}
</style>
<script src="usercheck.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>
<body>
<form>
Desired Username:
<input type="text" id="txt1"
onkeyup="checkUser(this.value)">
</form>
<p id="validateCheck"></p>
</body>
</html>
Basically, at the top we have the common head tags (If you do use this, please add the xml in the html tag :)). Then we have the simple stylesheet for the page, containing the correct, and wrong classes and the body styles (just the font size and the font family). Next we have the <script> tag containing the url to the javascript code (which we’ll write in a minute). And then finially the form that we will use to check whether a user exists or not.
This little piece of code (below) tests whether the user has typed anything, and if they have, then it calls the javascript function which interacts with the PHP file.
onkeyup="checkUser(this.value)"
Save this index file now. As you don’t want to loose any work.
Step 2) Creating the usercheck.js file
This is the ‘ajax’ file as it were, it contains all the code needed to get the data from the form in instant time, send it to the PHP file and get the end result from the PHP File. It will also check whether the user has ajax enabled on their browser, and, if they don’t, sends out an alert message saying that their browser does not support ajax. Very few browsers do not support ajax, the big 4 (IE Explorer, Google Chrom, FireFox and Safari) all support ajax.
Create a new file called ‘usercheck.js’ and save it in the same directory as the index.html file. Next, add the following code to your usercheck.js file and save it.
lfunction checkUser(str) // Creates a new checkUser function.
{
if (str.length==0) // checks if the str variable inside the checkUser function is equal to 0
{
document.getElementById("validateCheck").innerHTML=""; // Gets the html object by it's id, in this case it's id is validateCheck
return; // Returns the end result of the function
}
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) // Checks whether the users browser allows ajax
{
alert ("Please use a browser that has ajax enabled!"); // Alerts if the users browser does not support ajax
return; // Returns the function
}
var url="usercheck.php"; // Creates a new variable called url
url=url+"?user="+str; // Assigns an id to the php file (usercheck.php?id=user)
url=url+"&sid="+Math.random(); // Assigns a random math function to the url
xmlHttp.onreadystatechange=stateChanged; // If the forms state has changed
xmlHttp.open("GET",url,true); // Gets a pages content using ajax
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("validateCheck").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
Basically what this file does is it sends the variable from the textbox to the php file using PHP’s $_GET function. It also checks whether the users browser can support ajax. I have commented the necessary parts of this file for you, so youc an get a better understanding of the works of this project. Save this file, so we can work on the last and final page. The usercheck.php page.
Step 3) The usercheck.php file
Create a new file called ‘usercheck.php’ and save it to the same directory as the index and the usercheck.js file. This will be the main processing file, checking whether the user exists or not. It holds all the functions to connect to the database, checks whether the user exists and the outputs it.
Add the following code to your ‘usercheck.php’ file.
l<?php
$database_name = 'yourdbname'; // Enter your database name
$database_user = 'yourdbuser'; // Enter your database username
$database_pass = 'yourdbpass'; // Enter your database password
$database_host = 'yourdbhost'; // Enter your database hostname
$sql = mysql_connect($database_host,$database_user,$database_pass); // Connects to the mysql database
if(!$sql) // If it doesnt work
{
die('Error, couldnt connect to the database.'); // 'Die's with an error message
}
else // If it does work
{
$select_db = mysql_select_db($database_name); // Selects the database
if(!$select_db) // If it can't select the database
{
die('Couldnt connect to the database.'); // Die's an error message.
}
}
// Get the user id from URL
$user=htmlspecialchars(mysql_real_escape_string($_GET["user"]));
$query = mysql_query("SELECT * FROM users WHERE username = ‘" .$user."’") or die(mysql_error()); // Change users to the database where you keep your usernames, and likewise with username
list($user_id) = mysql_fetch_row($query);
$row = mysql_fetch_array($query);
if(empty($user_id))
{
$check = ‘<span class="correct">That username is available.</span>’;
}
else
{
$check = ‘<span class="wrong">That username is not available.</span>’;
}
// Echos whether the user exists or not.
echo $check;
?>
Now save this usercheck.php file. I’ll explain this file a little bit. At the top, we hold the mysql connection variables, please fill these in with your own mysql connection details. Next we have the actual mysql_connect function with a bit of troubleshooting. Following that, in the same if function we have the mysql select db function which selects the database, and again we have some troubleshooting.
After that, you will see a piece of code like this
$user=htmlspecialchars(mysql_real_escape_string($_GET["user"]));
This gets the user variable from the URL, and assigns it to a variable. As well as securing it against xss and sql injections.
After that we have the function that checks whether the username exists in the database, or not, and then assigns the appropriate output to the $check variable which will be echoed at the end of the script.
Final words
Thankyou for viewing this tutorial, I would love to put more detail into it, but I hope I’ve taught you the basics of live validation. You can now try out different methods, such as live email validation and checking whether a user has filled in a form or not. If you wish to download all the files used in this tutorial, then please check below for the link. Again, if you have any comments or improvements then please use the comment feature below. Thankyou :).
Blogsphere: TechnoratiFeedsterBloglines
Bookmark: Del.icio.usSpurlFurlSimpyBlinkDigg
RSS feed for comments on this post | TrackBack URI for this post






[...] View original here: SiteGale | ? New Ajax tutorial: Live user validation [...]
We absolutely love your blog and find the majority
of your post’s to be just what I’m looking for. Would you offer guest writers to write content in your case? I wouldn’t mind composing a post or elaborating on some of the subjects you write regarding here. Again, awesome blog!