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

%>

 

JavaScript utility popup boxes for better user interaction


JavaScript utility popup boxes for better user interaction:

 

  1. Alert Box – JavaScript pop up to display any information or error messages to the user.As JavaScript is a client side scripting language we can use this alert box to interact with the user.You can raise the alert message through some events or it can be used in debugging purpose.

    It can be used as a great debugging tool in Classic ASP or PHP or in large and complicated JavaScript.

    Image of Javascript Alert Popup box

    Javascript Alert Box

     

<HTML>

<HEAD>

<TITLE> Alert Test </TITLE>

<script type=”text/javascript”>

function showTheAlert(){

        alert(“Hi I have been called for”);

}

 

function showAlertWithMessage(msg){

        alert(“The message is : ” + msg );

}

 

</script>

</HEAD>

 

<BODY>

<h1>Simple Atert test</h1>

<input type=”button” name=”showAlert” onclick=”javascript:showTheAlert()”
value=”Show me the alert” />

 

<br/>

<h1>Custom alert with message</h1>

<input type=”text” name=”msgAlert” id=”msgAlert”/>

<input type=”button” name=”showMsgAlert” onclick=”javascript:showAlertWithMessage(document.getElementById(‘msgAlert’).value)” value=”Show me the alert” />

 

</BODY>

</HTML>

 

  1. Confirm Box: This is a very good JavaScript pop up box which confirms user action.Such as if you want the user to confirm his action like deletion of some important data this pop up box can be used. Image of Javascript confirm message box

    Jacascript Confirm Message box

     

<HTML>

<HEAD>

<TITLE> Confirm Test </TITLE>

<script type=”text/javascript”>

function ConfirmTest(){

        var conf = confirm(“Are you sure want to Perform this action ??”);

 

        if(true == conf){

                alert(“You have pressed the YES button”);

        }else{

                alert(“You have pressed the CANCEL button”);

        }

}

 

</script>

</HEAD>

 

<BODY>

<br/>

<h1>Confirm pop up box test</h1>

<input type=”button” name=”confrmBtn” onclick=”javascript:ConfirmTest()” value=”Show me the alert” />

</BODY>

</HTML>

  

  1. Prompt Box: This box is very useful if you want the user to input some text at the runtime or as a result of some action.Suppose you may want the user to enter his transaction password if he is performing some important action.Then this Prompt popup box may come handy.

    Notation of prompt is:

    prompt(“Your message”, ”default value you want to display”);

    If you want to display some default values you can specify that also by setting the second argument of this popup box.

      

<HTML>

<HEAD>

<TITLE>Prompt for user input Test </TITLE>

<script type=”text/javascript”>

function PromptTest(){

        var age = prompt(“Enter your age”,”99″);

       

        if(null != age && age != “undefined”){  

                alert(“Your age is: ” + age);

    }else{

                alert(“You have pressed the CANCEL button dear”);

    }

}

 

</script>

</HEAD>

 

<BODY>

<br/>

<h1>Prompt pop up box test</h1>

<h3>Click this button to enter your age </h3>

<input type=”button” name=”confrmBtn” onclick=”javascript:PromptTest()” value=”Show me the alert” />

 

</BODY>

</HTML>

 I think this popup boxes and the tutorial can help you to start exploring the technology of the web and JavaScript.

 Happy JavaScripting 🙂