Validate a username using Javascript and PHP ( AJAX )
on Saturday, August 11th, 2007 at 11:44 am

Who doesn’t hate these long forms ? You fill each field in them and when you submit, it will return something like :
‘ SORRY BUT YOUR USERNAME IS ALREADY TAKEN ‘.
In this tutorial I m gonna show you how to check if a username is valid without leaving the page using ajax (Asynchronous Javascript And XML).
Before I start, check the final result to see if this what you are looking for.
Demo: click here
Download files: click here
Ready ?
Lets roll
First of all what is AJAX ?
Ajax, or AJAX, is a web development technique used for creating interactive web applications. The intent is to make web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user requests a change. This is intended to increase the web page’s interactivity, speed, functionality, and usability.
Like DHTML, LAMP, and SPA, Ajax is not a technology in itself, but a term that refers to the use of a group of technologies.
Now lets see those files
- _ajax.new.js: is the main file. Javascript is the glue that connect the server side language to the HTML page.
- index.html: is the HTML page where the user sends its request and receives the answer
- ajax-test.php: is the php file where we will make all the database operations or simple checkings like string lenght etc…
_ajax.new.js:
We’ll start by creating a basic class, called Ajax, in which we’ll wrap the functionality of the XMLHttpRequest class
Note: I will not analyse the whole class here, i will just explain briefly some key functions.
I will do another tutorial later, on how to make an advanced Ajax class using javascript.
Here are the beginnings of our Ajax’s class constructor function.
This code just defines the properties we’ll need in our Ajax class in order to work with XMLHttpRequest objects.
this.req = null;
this.url = null;
this.status = null;
this.statusText = ”;
this.method = ‘GET’;
this.async = true;
this.dataPayload = null;
this.readyState = null;
this.responseText = null;
this.responseXML = null;
this.handleResp = null;
this.responseFormat = ‘text’, // ‘text’, ‘xml’, ‘object’
this.mimeType = null;
this.headers = [];
}
Now lets add an init method.
Here I am creating an XMLHttpRequest object. As you can see i tried to instantiate the object in a number of different ways, because XMLHttpRequest is implemented differently in Firefox, Safari, and Opera than it is in Internet Explorer.
Internet explorer 6 and earlier use a class called ActiveXObject while Firefox and Safari use class called XMLHttpRequest.
var i = 0;
var reqTry = [
function() {
return new XMLHttpRequest(); },
function() {
return new ActiveXObject('Msxml2.XMLHTTP') },
function() {
return new ActiveXObject('Microsoft.XMLHTTP' )} ];
while (!this.req && (i < reqTry.length)) {
try {
this.req = reqTry[i++]();
}
catch(e) {}
}
return true;
};
SENDING A REQUEST:
Now that we created an XMLHttpRequest, lets write a function that uses it to make a request.
Here are the steps
1- Calls init to create an instance of the XMLHttpRequest class and displays an alert if the call is not successful.
2- Call the open method on this.req this.req.open(this.method,this.url,this.async) to begin setting up the HTTP request.
The open method takes 3 parameters:
a- this.method ( GET or POST )
b- this.url ( the URL of the server side page )
c- this.async ( if this is set to true, then our javascript will continue to execute normally while waiting for a response. If you set it to false then our javascript will stop until the response comes back from the server… This should be set to true as this is the whole point of an AJAX application )
3-Set the headers of the page, depending on the method used
4-Setting up the onreadystatechange event handler.
As the HTTP request is processed by the server, its progress is indicated by these set of integers:
0: uninitialized
1: loading
2: loaded
3: interactive
4: completed
Now we have to wait until the request is completed ( state 4 ) so we can handle the response ( or maybe launch a function )
5-Processing the response.
When the response completes we should check first if the request succeeded. The status property contains the HTTP status code of the completed request.(now this could a 404 page or 500 page… )
But if req.status is bigger then 199 and smaller then 300 then we are ok ![]()
Note: a full list of the HTTP status code can be found here
Talaaaaaaaaa here’s the code
var self = null;
var req = null;
var headArr = [];
if (!this.init()) {
alert(‘Could not create XMLHttpRequest object.’);
return;
}
req = this.req;
req.open(this.method, this.url, this.async);
if (this.method == “POST”) {
this.req.setRequestHeader(
‘Content-Type’, ‘application/x-www-form-urlencoded’);
}
if (this.method == ‘POST’) {
req.setRequestHeader(
‘Content-Type’, ‘application/x-www-form-urlencoded’);
}
self = this; // Fix loss of scope in inner function(s)
req.onreadystatechange = function() {
var resp = null;
self.readyState = req.readyState;
if (req.readyState == 4) {
self.status = req.status;
self.statusText = req.statusText;
self.responseText = req.responseText;
self.responseXML = req.responseXML;
switch(self.responseFormat) {
case ‘text’:
resp = self.responseText;
break;
case ‘xml’:
resp = self.responseXML;
break;
case ‘object’:
resp = req;
break;
}
if (self.status > 199 && self.status < 300) {
if (!self.handleResp) {
alert('No response handler defined ' +
'for this XMLHttpRequest object.');
return;
}
else {
self.handleResp(resp);
}
}
else {
self.handleErr(resp);
}
}
}
req.send(this.dataPayload);
};
Now all what we still need is a URL and a HANDLER function for the response.
This method here will kick off the request.
this.url = url;
this.handleResp = hand;
this.responseFormat = format || ‘text’;
this.doReq();
};
index.html:
First lets call our Ajax class. Here we have 2 functions:
hand(): this function will handle the response received and will write it .
validateUsername(): this function will actually launch the ajax class and call the method doGet.
window.document.getElementById(‘response_span’).innerHTML=str;
}
function validateUsername(user){
var strDomain=”;
window.document.getElementById(‘response_span’).innerHTML=
“Validating username…”;
var ajax = new Ajax();
ajax.doGet(strDomain+’ajax-test.php?action=validateUsername&
username=’+user,hand,’text’);
}
The HTML:
| Choose your username |
size="30" onchange="validateUsername(this.value)"/> |
|---|
ajax-test.php:
All what this page does is check if the username is > then 3 characters and if it is equal to some pre-defined values.
You can easily change the code below to suit your needs and write some SQL statements in it.
case ‘validateUsername’:
$username = trim($HTTP_GET_VARS['username']);
if ( strlen($username) >= 3 ){
if ( $username == “joe” || $username == “rony”
|| $username== “joo” )
print “Username is valid“;
else
print “Username is not valid“;
}
else{
print “Username must be longer then
3 characters“;
}
break;
default:
//silence is golden
endswitch;
I hope i was comprehensible in my first big tutorial.
Just leave some comments and tell me your advices.
//Jo
Signing out
Peace
47 Comments »
[...] files Brief description: _ajax.new.js: is the main ajax class. I have already explained this class here _formdata2querystring.js: used for posting the element of a form _applogin.js: specific ajax class [...]
I couldn’t understand some parts of this article o.us poetry, but I guess I just need to check some more resources regarding this, because it sounds interesting.
[...] _ajax.new.js: is the main ajax class. I have already explained this class here [...]
error in demo code
ajax-text.php line 9
$username== “joo” should read $username== “moo”
When I’m testing this script it really won’t validate as it stops after writing “Validating username…”?
Suggestions?
[...] _ajax.new.js: is the main ajax class. I have already explained this class here [...]
I do appreciate that my name (“moo”) is in the valid usernames list .
A simple Guess! what does “xxx” refer to?
for those who want the script to check a MySQL database
here is the modified scritp
i’m new to php, mysql and ajax but i’m setting up a new website and wen i first tested this script, i could not get it to work using a database, but now after an half an our testing, i have managed to get is to work, and it works like a charm (at first sight)!
oh, and to peter i would like to say that it is probable the php version , on php 4.4.7 it works fine on my wamp test server (original and modified).
when using the standard unmodified version with php 5.2.5, i have the same error as you had…
[CODE]
= 3 ){
$query=(“Select * from user where uname=’$username’”);
$result= mysql_query($query);
$num=mysql_num_rows($result);
if ($num > 0) {//Username already exist
print “Username already exist”;
}else{
print “Username is valid”;
}}
else{
print “Username must be longer then 3 characters”;
}
break;
default:
//silence is golden
endswitch;
?>
[/CODE]
enjoy,
Hey Davy
Your code is neat, but gives me an error each time I want to use it:
=============
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in
==============
Running:
MySQL 5.1.23
PHP 5.2.5
Apache 2.2.6
It doesn’t make sense that I get these errors.
It should work
Any ideas?
Cheers
ok, look, first of; thanks for writing fairly clear tutorial in English language. I really appriciate of this style, which make lots of things clear in a little sentence.
2nd tutriols are really nice with out errors if someone is using IE 7…. with firefox beta 3 has some problems. it also works pretty well in Safari for win and Opera for win.
So, thanks again and carry on, it really helps me a lot. the people who have some idea about web development but learning for new comming standards for web……….
c.u
Thank you
so simply and easier to understand than other scripts. I did it with database connection and it worked so fast! Thank you again
I keep getting Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource any one have any idea why?
its refering to this area
$query=(“Select * from inv_user where userid=’$username’”);
$result = mysql_query($query);
$num = mysql_num_row($result);
if ($num > 0) {//Username already exist
You’re getting this error because when you copy ad paste the code above it changes qutation mark into another completely defferent one. Simple change any double qutations into the one you have in your keyboard.
It works fine with me and I’ve developed it according to my needs. The only problem which this code doesn’t deal with is the Middle East charsets!! I’m trying to integrate it with such charsets and if anyone has any idea how to solve this, I would be more than appreciated.
Regards,
[...] 3.1 Validate a username using Javascript and PHP ( AJAX ) [...]
[...] 3.1 Validate a username using Javascript and PHP ( AJAX ) [...]
This code suxx:
- it’s written in php
- your database queries are done in your views
- you got a hudge sql injection hole
- your switch return html instead of plain text
- your html is html 4.0
it’s nice from you to post newbie code for ultra newbies, but appearly, you didn’t resolved his prob and you learn him the worst way to code..
I’m not really surprised… it’s php, it’s newb, that’s automatic.
@Mulasse: Well maybe when you write your script drop me an email and i will check it
[...] Validate a username using Javascript and PHP ( AJAX ) [...]
[...] 3.1 Validate a username using Javascript and PHP ( AJAX ) [...]
When I’m testing this script it really won’t validate as it stops after writing “Validating username…”?
Suggestions?
Same as last years poster. No matter what’s done their’s no response text on failure or or acceptance.
[...] 3.1 Validate a username using Javascript and PHP ( AJAX ) [...]
[...] 3.1 Validate a username using Javascript and PHP ( AJAX ) [...]
Hi there,
Seems like a good tutorial, currently I’m reading it – just finished to read the 1st page.
Though I think that it would be important to notice you that the “Demo” & “Download files” are not contain anything – they are empty.
Yours,
Yoni D.
Hello i want code in PHP to validate the HTTTP_AUTH_LOGIN ie when user enters the username and password wrong 3 times and at 4th attempt the login page should be exited. plz help me thanks in advance.
Validate a username using Javascript and PHP ( AJAX ) at FARAWAY great article thank you.
[...] 3.1 Validate a username using Javascript and PHP ( AJAX ) [...]
Hello i want code in PHP to validate the HTTTP_AUTH_LOGIN ie when user enters the username and password wrong 3 times and at 4th attempt the login page should be exited. plz help me thanks in advance.
Hello i want code in PHP to validate the HTTTP_AUTH_LOGIN ie when user enters the username and password wrong 3 times and at 4th attempt the login page should be exited. plz help me thanks in advance.
[...] Validate a username using Javascript and PHP ( AJAX ) [...]
It´s better if you use onblur=validateUsername(this.value) but anyway thanks a lot!
[...] Validate a username using Javascript and PHP ( AJAX ) [...]
Thanks nice blog.
[...] 3.1 Validate a username using Javascript and PHP ( AJAX ) [...]
RSS feed for comments on this post. TrackBack URL