Validate a username using Javascript and PHP ( AJAX )

_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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
  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.

1
2
3
4
5
6
  this.doGet = function(url, hand, format) {
    this.url = url;
    this.handleResp = hand;
    this.responseFormat = format || 'text';
    this.doReq();
  };

Popularity: 35% [?]

14 Responses to “Validate a username using Javascript and PHP ( AJAX )”


  1. 1 Daniel

    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.

  2. 2 Steve

    error in demo code

    ajax-text.php line 9

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

  3. 3 Peter

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

  4. 4 moo

    I do appreciate that my name (”moo”) is in the valid usernames list .

    A simple Guess! what does “xxx” refer to?
    :)

  5. 5 dinesh

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

  6. 6 Jo

    nice work..

  7. 7 Davy

    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,

  8. 8 M. Dubb

    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

  9. 9 M. Dubb

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

    Thank you for the idea.

  10. 10 hasan

    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

  11. 11 Electrominds

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

  12. 12 hanu

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

  13. 13 Luke70

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

  14. 14 ABC

    poor

  1. 1 Ajax login form (PHP & Javascript) - FARAWAY
  2. 2 Google Pagerank using Ajax at FARAWAY
  3. 3 Ajax login form (PHP & Javascript) « Tancheng’s Weblog

Leave a Reply