Create a Simple Application to Search a User Name from Database in AJAX


Hi,

Many of us does not know how to use AJAX and roaming in the Internet for one sample application from which we can start building our knowledge in AJAX (Asynchronous JavaScript and XML).

 

I have a small web application whose backend database is in MySQL and the Server side scripting language is PHP (Hypertext Pre Processor).

 

First we should why we need AJAX in our application. We were pretty happy with our own standard applications where we use POST or GET method to go to database and Fetch data and display it in the Page.

 

In the earlier cases if we want a small database access then also we need to POST the form with variables and then execute the Database query and then fetch and Display data back in the Browser.

 

Suppose we want to validate a user name, i.e we want to check if the user name already exists or not before inserting the user details in the database.

 

In this case we need 2 server accesses.

 

  1. First time send data to server to check the user name from database.
  2. GET Data back to the Client with the details such as the name already exists or Name does not exist.
  3. Again send the full form in the server with the complete user details to insert the user in the database.

 

So, if our form is pretty long and contains images and JavaScripts other stuffs then these elements will load again along with the form. This will hamper the performance of the site.

 

So we can use AJAX here to minimize the load time and Access time.

 

As we know AJAX is not a new coding language. It is a Methodology. This methodology uses XMLHTTP Request to send data to server and get back the results with JavaScript.

 

Now we will create a JavaScript document named ServerReq.js, which will contain all the utility functions that we can use through out the application.

 

/*

* File: ServerReq.js

*This file creates the instance of xmlHttpRequest object, sends and

* Receives the request and response respectively.

*/

/*

* Static script to instantiate XMLHttp object for different browsers.

*/

var clientHttpHandler;

clientHttpHandler = create();

 

/*

* This method creates the xmlHttpRequest object and returns it.

*/

function create()         

{

            var xmlHttpRequest = false;

 

            //Internet Explorer

            try

            {

                        xmlHttpRequest = new ActiveXObject(“Msxml2.XMLHTTP”);

            }

            catch (xml2Exception)

            {

                        try

                        {

                                    xmlHttpRequest = new ActiveXObject(“Microsoft.XMLHTTP”);

                        }

                        catch (xmlException)

                        {

                                    xmlHttpRequest = false;

                        }

            }

 

            //Netscape, Mozila, Firefox, Safari, Opera

            if (!xmlHttpRequest && typeof XMLHTTPRequest == ‘undefined’)

            {

                        try

                        {

                                    xmlHttpRequest = new XMLHttpRequest();

                        }

                        catch (genException)

                        {

                                    XMLHttpRequest = false;

                        }

            }

            return xmlHttpRequest;

}

/*

* This method sends the request to the server url according to the

* Passing parameters. It sets the user’s response function to the

* onreadystatechange event of the xmlHttpRequest object.

*/

function send(httpMethod, serverUrl, isAsync, respFunc)

{

            clientHttpHandler.open(httpMethod, serverUrl, isAsync);

            clientHttpHandler.onreadystatechange = respFunc;

            clientHttpHandler.send(null);

}

/*

* This method checks the state and the status of the response and

* Depending on that fetches the response text.

* readystate: 0 – uninitialized, 1 – loading, 2 – loaded, 3 – interactive, 4 – complete

*/

function receive()

{

            //var response = “”;

            try

            {

                        if (clientHttpHandler.readyState == 4) // Completed

                        {

                                    if (clientHttpHandler.status == 200) // “OK”

                                    {

                                                return true;

                                    }

                                    else if (clientHttpHandler.status == 403) // “Forbidden”

                                    {

                                                alert(“Error: Access denied. Please check the permissions!”);

                                    }

                                    else if (clientHttpHandler.status == 404) // “URL Not Found”

                                    {

                                                alert(“Error: URL not found. Please check the URL!”);

                                    }

                                    else // Miscellaneous

                                    {

                                                alert(“Error: status code ” + clientHttpHandler.status);

                                    }

                        }

                        return false;

            }

            catch (genException)

            {

            }

}

 

 

In this function we have created an XMLHttpRequest object depending on the type of browser.

Then we have used the OnReadyStateChange event of the Object that will check if the Request has been completed or not.

 

This event has 4 ready states:

 

State

Description

0

The request is not initialized

1

The request has been set up

2

The request has been sent

3

The request is in process

4

The request is complete

 

 

So each time the ready state changes the function receive() will be executed.

But we will look for the ready state 4 as in this state the request is marked as completed. SO whatever request we have sent that is being completed and we can now access the response data now.

 

Now we will create a Function that will use the above script to send, parse and display data to the webpage from where we have requested it.

 

/*

* File: SendAjaxRequest.js

This function we will call from our webpage with the values that

Needs to be sent to the server for processing.

*/

 

function SendReqSearchRequest(userName){

         /*

          We will append a random number each time we need to

          Send the request. So that browsers does not cache the request

          And every time a fresh page will be executed.

         */

        var rand = Math.floor(Math.random()*1000001);

             

        // The URL where our background page resides

 

         sURL = “../utility/searchuser.php”; // I have used a relative path

           

            /*

         I have here used the GET method to send data to the background

         Page so builds the query string here.

         */

         queryString = “?rand=” + rand + “&username=” + userName;

           

         // Append the query string at the end of the URL

 

            sURL += “?” + queryString;

                       

            //Attach a function which will take care of the data when it comes back

 

         clientFunc = populateSearchResultData;

 

         // If this request is a synchronous or not.

         // If we use multiple synchronous requests at a time then only the

        // Last request will be executed.

 

            isSync = true;

    

        // Now send the request.

 

            send(“GET”, sURL, isSync, clientFunc);

           

}

 

/*

* This method populates the returrn data

*/

function populateSearchResultData ()

{

            var opStr = “”;

 

            if (receive())

            {

                         response = clientHttpHandler.responseText;

                       

                         if(response == “NF”){

                                    document.getElementById(“ResultDiv”).innerHTML = “User name OK”;

                         }else{

                                  document.getElementById(“ResultDiv”).innerHTML = “User name Already in Databse<br/> Choose a different one.”;

 

                   }  

            }

}

 

 

Now we will create our background page searchuser.php, which will search the user name from the data we pass to it.

 

<?php

 

//1. Conenct to Databae Here

 

//2. Select the Database

 

//Check if the user name variable is set or not as without it we cannot search

 

 

if(isset($_REQUEST[‘username’])){

 

            // Build the query string

            $name = $_REQUEST[‘username’];

 

            $query = “SELECT user_name FROM tbl_user WHERE user_name = ‘{$name}'”;

 

            // Now fire the query

 

            $result = mysql_query($query);

 

            if(mysql_num_rows($result) > 0){

                        //User found

 

                        echo “OK”;

            }else{

 

                        //User NOT found

 

                        echo “NF”;

            }

}else{

 

            echo “ERROR”;

}

 

?>

 

 

Now this page will search the user name in the background and outputs specified string, which will send back the Client to process as per requirement.

 

 

And now we require one more page before we proceed to Test.

 

 

This page is the main page of our application from where user creation is done. I have used only one element to demonstrate the AJAX technology; you can use it anywhere you like.

 

Name of the file: AddUser.html

 

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>

<HTML>

<HEAD>

<TITLE> AJAX Test Page </TITLE>

<META NAME=”Generator” CONTENT=”EditPlus”>

<META NAME=”Author” CONTENT=””>

<META NAME=”Keywords” CONTENT=””>

<META NAME=”Description” CONTENT=””>

<script type=”text/javascript” src=”js/ServerReq.js”></script>

<script type=”text/javascript” src=”js/SendAjaxRequest.js”></script>

<script type=”text/javascript”>

function checkUserName(){

            user =  document.getElementById(“username”);

          if(null == user or user.value == “”){

            alert(“Please enter a User Name to check “);

         }

            SendReqSearchRequest(user);

}

</script>

 

</HEAD>

 

<BODY>

<form method=”POST”>

User Name : <input type=”text” name=”username” id=”username”/>

<a href=”#” onlcick=”javascript:checkUserName()”> check user name </a><br/>

<div id=”ResultDiv”></div><br/>

Password : <input type=”password” name=”pass” id=”pass” /> <br/>

Confirm Password : <input type=”password” name=”confpass” id=”confpass” /> <br/>

 

<input type=”submit” name=”submit” value=”Add user”/>

 

</form>

 

</BODY>

</HTML>

 

Here if the users click on the “check user name” link, the function will be called and JavaScript will send the request to the server in the background. In the mean time users can proceed filling the form. This form will be ready.

 

When the response data comes back from the server it will be displayed in the Div.

 

Also, Do not forget to add this JavaScripts at the TOP:

 

<script type=”text/javascript” src=”js/ServerReq.js“></script>

<script type=”text/javascript” src=”js/SendAjaxRequest.js“></script>

 

You can note from these above lines that the Scripts are located in the js folder under the root directory.

 

Important: As ServerReq.js holds the necessary functions to create and use the XMLHTTPRequest object then you always need to include the script ServerReq.js before using the Object.

 

HappY AjAxing 😉

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s