Validate a username using Javascript and PHP ( AJAX )

on Saturday, August 11th, 2007 at 11:44 am

Ajax Logo
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.

function Ajax() {
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.

this.init = function() {
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 :D
Note: a full list of the HTTP status code can be found here

Talaaaaaaaaa here’s the code

this.doReq = function() {
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.doGet = function(url, hand, format) {
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.

var hand = function(str){
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.

switch ( $action ):
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 :)

| Posted in Ajax, PHP, Tutorials | 47 Comments »

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 [...]

Pingback by Ajax login form (PHP & Javascript) - FARAWAY | September 22, 2007 @ 8:10 pm

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.

Comment by Daniel | September 27, 2007 @ 7:17 am

[...] _ajax.new.js: is the main ajax class. I have already explained this class here [...]

Pingback by Google Pagerank using Ajax at FARAWAY | November 13, 2007 @ 2:27 pm

error in demo code

ajax-text.php line 9

$username== “joo” should read $username== “moo”

Comment by Steve | November 15, 2007 @ 11:35 am

When I’m testing this script it really won’t validate as it stops after writing “Validating username…”?
Suggestions?

Comment by Peter | November 19, 2007 @ 1:11 am

[...]   _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?
:)

Comment by moo | December 26, 2007 @ 2:23 am

Thanks Its really a good thing! Good work tom. Well done

Comment by dinesh | January 23, 2008 @ 2:51 pm

nice work..

Comment by Jo | January 24, 2008 @ 2:43 am

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,

Comment by Davy | March 13, 2008 @ 9:11 pm

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

Comment by M. Dubb | April 13, 2008 @ 11:53 am

Fixed it.
No idea what it was but it works now.

Thank you for the idea.

Comment by M. Dubb | April 13, 2008 @ 7:32 pm

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

Comment by hasan | May 9, 2008 @ 8:35 pm

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 ;)

Comment by Electrominds | May 22, 2008 @ 5:31 pm

Its very useful beginners of Ajax Like me… thank u very much..

Comment by hanu | May 29, 2008 @ 11:37 am

Very nice scritp, I’ll use it with MySQL.
I’ll let you know.

Comment by Luke70 | June 30, 2008 @ 5:15 pm

poor

Comment by ABC | August 29, 2008 @ 8:20 am

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

Comment by eric | October 3, 2008 @ 6:37 am

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,

Comment by Hi eric | October 7, 2008 @ 4:37 pm

[...] 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.

Comment by Mulasse | November 4, 2008 @ 12:06 pm

@Mulasse: Well maybe when you write your script drop me an email and i will check it :)

Comment by Jo | November 4, 2008 @ 12:11 pm

[...] Validate a username using Javascript and PHP ( AJAX ) [...]

Pingback by +50 Ejemplos en Ajax | ProyectoAurora.com | November 4, 2008 @ 2:59 pm

[...] 3.1 Validate a username using Javascript and PHP ( AJAX ) [...]

111

Comment by 11 | November 11, 2008 @ 6:23 am

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.

Comment by Jim | November 12, 2008 @ 3:31 am

[...] 3.1 Validate a username using Javascript and PHP ( AJAX ) [...]

[...] 3.1 Validate a username using Javascript and PHP ( AJAX ) [...]

very good

Comment by halı yıkama | January 16, 2009 @ 12:15 am

could you put a link for the zip file?
thx

Comment by arni | February 4, 2009 @ 11:54 am

@arni:
http://www.joeabiraad.com/demos/ajax1/ajax1.zip

Comment by Jo | February 4, 2009 @ 11:58 am

I really liked the way they came off

Comment by taylor | March 4, 2009 @ 3:17 am

Thanks very nice.

Comment by halı yıkama | March 21, 2009 @ 10:17 am

thanx

Comment by sdfsdfsdf | April 5, 2009 @ 6:25 pm

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.

Comment by Yoni D | April 28, 2009 @ 7:00 pm

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.

Comment by Shashidhar | May 25, 2009 @ 4:40 pm

Validate a username using Javascript and PHP ( AJAX ) at FARAWAY great article thank you.

Comment by dağıtım | July 29, 2009 @ 4:09 pm

Thanks for the great and simple tutorial !

Comment by Victor | September 23, 2009 @ 9:53 am

great article thank you.

Comment by moto kurye | September 23, 2009 @ 12:47 pm

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.

Comment by e okul | February 17, 2010 @ 8:26 pm

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.

Comment by Medyumlar | May 21, 2010 @ 1:02 pm

[...] Validate a username using Javascript and PHP ( AJAX ) [...]

It´s better if you use onblur=validateUsername(this.value) but anyway thanks a lot!

Comment by Menio | June 30, 2010 @ 5:01 pm

[...] Validate a username using Javascript and PHP ( AJAX ) [...]

Thanks nice blog.
[...] 3.1 Validate a username using Javascript and PHP ( AJAX ) [...]

Comment by alihan | June 13, 2011 @ 9:40 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment