| PHP and AJAX - Check if the Username Exists in Real-time |
 |
This tutorial will show you how to make an AJAX feature which will allow you to tell the user if the username they entered is still available, without them having to reload the page. This tutorial will not show you how to make a user system, but will show you how you can add onto an existing one, so that users can almost instantly be informed about the status of the username they want.
Now, if you are not adding this to an existing registration system, you will have to setup a database to hold the usernames, for this tutorial. So first, create a database and then run this script below (fill in your connection information). It will create a simple table in the database and add a few usernames which you can change if you want, they are just being entered as an example. Save this as create.php, run it once and then delete it.
 |
<?php
mysql_connect ('localhost', 'USERNAME', 'PASSWORD');
mysql_select_db('DATABASE');
mysql_query("CREATE TABLE `users` (
`username` varchar(20) NOT NULL
) TYPE=MyISAM;");
mysql_query("INSERT INTO `users` VALUES('username');");
mysql_query("INSERT INTO `users` VALUES('example');");
?>
|
 |
Code Breakdown:
mysql_connect ('localhost', 'USERNAME', 'PASSWORD'); - This connects to MySQL, make sure you change the username and password to your information. (also change the localhost, if required)
mysql_select_db('DATABASE'); - This selects the database, make sure you fill it in with your database name that you made for this tutorial.
mysql_query("INSERT INTO `users` VALUES('username');"); - You can add more of these lines and/or change the value, this just make usernames in the database when we test our script at the end of the tutorial.
This script will be an example of a form field where the user would type in the username they want. Save this as form.php
 |
<script type="text/javascript">
function toggle_username(userid) {
if (window.XMLHttpRequest) {
http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
handle = document.getElementById(userid);
var url = 'ajax.php?';
if(handle.value.length > 0) {
var fullurl = url + 'do=check_username_exists&username=' + encodeURIComponent(handle.value);
http.open("GET", fullurl, true);
http.send(null);
http.onreadystatechange = statechange_username;
}else{
document.getElementById('username_exists').innerHTML = '';
}
}
function statechange_username() {
if (http.readyState == 4) {
var xmlObj = http.responseXML;
var html = xmlObj.getElementsByTagName('result').item(0).firstChild.data;
document.getElementById('username_exists').innerHTML = html;
}
}
</script>
<input id="username" type="text" name="username" onchange="toggle_username('username')" /><br />
<div id="username_exists" style="font-size: 11px;font-weight: bold;color:#FF3300"> </div>
|
 |
This tutorial is assuming the reader knows atleast basic HTML and CSS, so I am not going to explain that, but I will explain the basics of what the Javascript is doing.
if (window.XMLHttpRequest) { - This is checking if the browser is IE or not. If it returns true it is not IE and uses the handle for non-IE browsers. If it is IE then it will use a different function to create the handle.
handle = document.getElementById(userid); - This creates a handle for the username form, so we can retrieve the value.
var fullurl = url + 'do=check_username_exists&username=' + encodeURIComponent(handle.value); - This assembles the query string which we will use to make the request, although the "do=check_username_exists" is unnecessary in this case because this tutorial only has one type of request being made to ajax.php, people often add more ajax features to their site, so instead of making a new file for each one you can just make put "do=some_other_action" in the URL to differentiate other actions. This will be more clear later on when we make ajax.php.
http.open("GET", fullurl, true); - This will open the URL and retrieve the result.
http.onreadystatechange = statechange_username; - This will set the function to handle the result.
var html = xmlObj.getElementsByTagName('result').item(0).firstChild.data; - The result is in the form of an XML file, so this will get the tag with the name "result" and get the data in it, e.g. <result>This is the data in it</result>.
document.getElementById('username_exists').innerHTML = html; - This will output the result on the page.
The last script you will need to make will do all the PHP work for the other script, save this as ajax.php
 |
<?php
mysql_connect ('localhost', 'USERNAME', 'PASSWORD');
mysql_select_db('DATABASE');
$do = $_GET['do'];
switch($do) {
case 'check_username_exists':
if(get_magic_quotes_gpc()) {
$username = $_GET['username'];
}else{
$username = addslashes($_GET['username']);
}
$count = mysql_num_rows(mysql_query("SELECT * FROM `users` WHERE `username`='".$username."'"));
header('Content-Type: text/xml');
header('Pragma: no-cache');
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<result>';
if($count > 0) {
echo 'That username already exists, please select another one.';
}else{
echo 'That username is available.';
}
echo '</result>';
break;
default:
echo 'Error, invalid action';
break;
}
?>
|
 |
Code Breakdown:
mysql_connect ('localhost', 'USERNAME', 'PASSWORD'); - This connects to MySQL, make sure you change the username and password to your information. (also change the localhost, if required)
mysql_select_db('DATABASE'); - This selects the database, make sure you fill it in with your database name that you made for this tutorial.
switch($do) { - As I explained before, this is not needed for this tutorial but it is there if you are going to use other AJAX features on your site, so you can keep it all in one file.
if(get_magic_quotes_gpc()) { - This will check if magical quotes is on, and it is enabled by default. What is magical quotes? It is supposed to be a security measure in PHP to prevent SQL injection, so in other words, if someone entered ' or " in a form it would make it so those quotes are canceled out with a slash (). Magical quotes can lead to a lot of confusion and trouble, but this script will add slashes if it is not enabled.
$count = mysql_num_rows(mysql_query("SELECT * FROM `users` WHERE `username`='".$username."'")); - This will return the number usernames in the database which match the username the user entered. It should return 0 or 1.
header('Content-Type: text/xml'); - This will change the header type so it will expect XML output.
echo '<result>'; - This will make a XML element called result, which as you may have guessed, will hold the result.
Now upload everything and open the form.php script in your browser, and type in a username. Here is my result for a username that exists:

It may not be pretty but it gets the point across and should be easy to integrate into a script and/or customize.
|
|
|
Date Added: 21-04-2008
Votes: 2
Rating: 7
Views: 13430
Author: admin
Main Category: PHP
Sub-Category: User Systems
|
 |
|
|
|