An AJAX Class: To use AJAX (Asynchronous JavaScript and XML) in a better way


An AJAX Class: To use AJAX (Asynchronous JavaScript and XML) in a better way

Class: clsAjax.js

 

// JavaScript Document

/*

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

* receives the request and response respectively.

* @Author Udaybhanu Karmakar

*/

/*

* Static script to instantiate XMLHttp object for different browsers.

*/

 

function ServerXMLHTTPRequest()

{

          this.clientHttpHandler = create();

          this.httpMethod = “GET”;

          this.serverUrl = “”;

          this.isAsync = true;

          this.respFunc = “”;

          this.send = function () {

                                                if(this.serverUrl != “”)

                                                 {

                                                          this.clientHttpHandler.open(this.httpMethod, this.serverUrl, this.isAsync);

                                                          this.clientHttpHandler.onreadystatechange = this.respFunc;

                                                          this.clientHttpHandler.send(null);

 

                                                 }

                                      };

          this.receive = receive;       

}

 

 

/* This method creates the xmlHttpRequest object and returns it.

*/

function create()     

{

          var xmlHttpRequest = false;

 

          //Internet Explorer

          try{

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

                   //alert(“creating new Msxml2.XMLHTTP obj”);

          }catch (xml2Exception){

                   try{

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

                             //alert(“creating new Microsoft.XMLHTTP obj”);

                   }catch (xmlException){

                             xmlHttpRequest = false;

                   }

          }

 

          //Netscape, Mozila, Firefox, Safari, Opera

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

                   try{

                             //alert(“creating new ff obj”);

                             xmlHttpRequest = new XMLHttpRequest();

                   }catch (genException){

                             XMLHttpRequest = false;

                   }

          }

         

          if (!xmlHttpRequest && window.createRequest){

                   try{

                             xmlHttpRequest = window.createRequest();

                   }catch (e){

                             xmlHttpRequest=false;

                   }

          }

 

          return xmlHttpRequest;

}

 

/*

* 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 status = null;

          try{

                   if (this.clientHttpHandler.readyState == 4){

                             status = this.clientHttpHandler.status;

                             if (status == 200){

                                      return true;

                             }

                   }

                   return false;

          }catch (genException){

                   alert(“Error accessing Data.\nStatus returned: ” + status);

          }

}

 

//Destructor

 

function destructObj(objToDestroy){

          objToDestroy = null; 

}

  

Suppose we have one text box and one button in a HTML page.

 

From this page users can add their emails in the mailing list by adding their email in the text box and clicking on the save button.

 

So in HTML first we have to create a page to display on text box and one button.

 

Page: addUserToMailingList.html

 

<html>

<head>

<title>Ajax Class Example – Mailing List</title>

</head>

<body>

<h1>Add my email to mailing list </h1>

<table width=”80%” border=”0″>

  <tr>

    <td width=”17%”>Email Address </td>

    <td width=”23%”><input name=”txtEmail” type=”text” id=”txtEmail”> </td>

    <td width=”60%”><input type=”button” name=”saveBtn” value=”Add email”></td>

  </tr>

</table>

</body>

</html>

 

Now in the onclick event for the Add email button we have to fire some code to save the email in the Mailing list in the background.

 

So after adding the JavaScript in the head section and adding the event listener for the Save button the HTML page now becomes:

 

<html>

<head>

<title>Ajax Class Example – Mailing List</title>

<script type=”text/javascript” src=””></script>

<script type=”text/javascript”>

var ajaxObject = null;

var response = null;

 

function saveEmail(){

          var emailAddr = document.getElementById(“txtEmail”).value;

          sendSaveEmailRequest(email);

}

 

/*

Function to send

*/

 

function sendSaveEmailRequest(email){

 

          //Initialize the Ajax Object

         

          if (ajaxObject == null){

                   ajaxObject = new ServerXMLHTTPRequest();

          }

                  

          //The url of the backend page to add the email address in Database

          serverURL = “save.user.emaillist.asp”;

          //Add the email address as query string

          //Add a random number at the end to stop IE caching

          queryString = “?userEmail=” + email + “&random=” + Math.random();

 

          if (queryString != “”){

                   serverURL += “?” + queryString;

          }

         

          if (serverURL != “”){

                             //Give the backgound page URL

                             ajaxObject.serverUrl = serverURL;

                             //Give the function name to execute after processing

                             ajaxObject.respFunc = receiveChangeData;

                             //Send asynchoronous request

                             ajaxObject.isAsync = true;

                             //Send the request

                             ajaxObject.send();

          }

}

 

function receiveChangeData(){

          if (ajaxObject.receive()){

                   //Destroy the response object for better use.

                   //There might be data of the previous call.

                  

                   if(response != null){

                             response = null;

                   }

 

                   //Now get the response as text

                   response = ajaxObject.clientHttpHandler.responseText;

                  

                   var str = “”;

                  

                   //If the backend page gives output as “OK” the user email successfully added

                  

                   if(response==’OK’){                     

                             alert(“User email added successfully in the email list”);             

                            

                   }else if(response==’NOK’){ //Else there is some problem adding

                             alert(“There is some problems adding user in the email list. \n Please check.”);

                   }

                   //Now destruct the object

                   destructObj(ajaxObject);

          }

}

</script>

</head>

<body>

<h1>Add my email to mailing list </h1>

<table width=”80%” border=”0″>

  <tr>

    <td width=”17%”>Email Address </td>

    <td width=”23%”><input name=”txtEmail” type=”text” id=”txtEmail”> </td>

    <td width=”60%”><input type=”button” name=”saveBtn” value=”Add email” onClick=”javascript:saveEmail()”></td>

  </tr>

</table>

</body>

</html>

 

 

Now we should create one backend page i.e save.user.emaillist.asp to save the data:

 

 

Page save.user.emaillist.asp

 

<%@LANGUAGE=”VBSCRIPT” CODEPAGE=”1252″%>

<%

Dim userEMail

 

userEMail = Request.QueryString(“userEmail “)

‘If email is not blank then add it to Database

 

If userEMail <> “” Then

‘Add user in Database

‘If addition success then

‘Response.write(“OK”)

‘Else

‘Response.write(“NOK”)

End If

%>

 

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 😉