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

%>

 

Saving HTML Form Data to XML by ASP


Storing your form submissions in XML

Usually form submissions in ASP are written to some sort of database management system. However, if you need your form submission data to be more portable, it can be written to an XML file. This is especially useful when the data you are gathering on your Web site will be sent to applications on non-Windows platforms. Since XML is completely portable across all platforms the data will not need to be converted.

In order to write a form submission to an XML document, it is necessary to create a new XML document using the Microsoft XMLDOM Object. The XMLDOM Object has an extensive object library that can be used to create the elements, attributes, and values that will make up the XML document. I will not cover the entire object model, because it is very extensive and could make up an entire section of this Web site by itself.

After the XMLDOM Object has been instantiated, the structure of the XML must be laid out by creating object references to the elements that make up each layer of the XML document. The following is an example of how the XMLDOM would be instantiated and a reference to the root element created. After the root element is created, it is appended to the XMLDOM Document. Then child elements are created and appended to the root element and then the document is saved.

Instantiating the Microsoft XMLDOM Object:

 
<%
 Dim objDom
 Dim objRoot
 Dim objChild1
 Dim objChild2
 Dim objPI
 
 
 'Instantiate the XMLDOM object using the CreateObject Method of the
 'Server Object.
 Set objDom = Server.CreateObject("Microsoft.XMLDOM")
 
 
 'Create a reference to an IXMLDOMElement (XML Element) Object by
 'calling the createElement Method of the XMLDOM. The createElement
 'Method accepts one paramter, a string representing the name of the
 'element. The return value is passed to the objRoot variable. This
 'element reference will represent the root element of the XML
 'Document.
 Set objRoot = objDom.createElement("rootElement")
 
 
 'Use the appendChild Method of the XMLDOM Object to add the objRoot
 'Element Reference to the XML Document.
 objDom.appendChild objRoot
 
 
 'Now, following the same steps, you will create references to the
 'child elements for the XML Document. The only difference is, when the
 'child elements are appended to the document, you will call the
 'appendChild Method of the IXMLDOMElement Object rather than the
 'appendChild Method of the XMLDOM Object. By using the IXMLDOMElement
 'to append the children, you are differentiating (and applying tiered
 'structure to) the child elements from the root element.
 
Set objChild1 = objDom.createElement("childElement1")
 objRoot.appendChild objChild1
 
 Set objChild2 = objDom.createElement("childElement2")
 objRoot.appendChild objChild2
 
 
 'The final step to take care of before saving this document is to add
 'an XML processing instruction. This is necessary so that XML parsers
 'will recognize this document as an XML document.
 Set objPI = objDom.createProcessingInstruction("xml","version='1.0'")
 
 
 'Call the insertBefore Method of the XMLDOM Object in order to insert
 'the processing instruction before the root element (the zero element
 'in the XMLDOM childNodes Collection).
 objDom.insertBefore objPI, objDom.childNodes(0)
 
 
 'Calling the Save Method of the XMLDOM Object will save this XML
 'document to your disk drive. In this case, the document will be saved
 'to the "c:" drive and will be named "MyXMLDoc.xml". When saving an
 'XML document, if the file does not exist, it will be created. If it
 'does exist, it will be overwritten.
 objDom.Save "c:\MyXMLDoc.xml"
%>

Once the document has been saved, if you open the document it will look like the following code listing.

MyXMLDoc.xml:

 
<?xml version="1.0"?>
<rootElement>
 <childElement1 />
 <childElement2 />
</rootElement>

In the “MyXMLDoc.xml” document, the childElement1 and childElement2 elements are rendered as empty elements. If they contained values each would have been rendered with opening and closing tags enclosing the value of the element.

Now, lets consider the idea of writing an HTML form submission to an XML document. We saw above how we could create and save an XML document. Writing a form submission to an XML document just becomes a matter of iterating through the Request Object’s Form Collection and writing the value of each form field to an XML element value. This can be accomplished with Active Server Pages.

Example: Sending Form Submissions to XML

Below is a normal HTML form that we will be using for this example. This form asks for the user’s name, address, telephone number, and e-mail address. This information will be written to an XML file for storage.

EnterContact.html:

 
<html>
<head>
 <title>
  Contact Information
 </title>
</head>
<body>
 <form action="processForm.asp" method="post">
  <h3>Enter your contact information</h3>
  First Name: <input type="text" id="firstName" name="firstName"><br>
  Last Name: <input type="text" id="lastName" name="lastName"><br>
  Address #1: <input type="text" id="address1" name="address1"><br>
  Address #2: <input type="text" id="address2" name="address2"><br>
  Phone Number: <input type="text" id="phone" name="phone"><br>
  E-Mail: <input type="text" id="email" name="email"><br>
  <input type="submit" id="btnSub" name="btnSub" value="Submit"><br>
 </form>
</body>
</html>

The action for this HTML form is set to processForm.asp. This is an ASP page that will call a function which iterates through the form fields and writes their values to an XML file.

processForm.asp:

 
<%
 
'--------------------------------------------------------------------
'The "ConvertFormtoXML" Function accepts to parameters.
'strXMLFilePath - The physical path where the XML file will be saved.
'strFileName - The name of the XML file that will be saved.
'--------------------------------------------------------------------
 
Function ConvertFormtoXML(strXMLFilePath, strFileName)
 
 'Declare local variables.
 Dim objDom
 Dim objRoot
 Dim objField
 Dim objFieldValue
 Dim objattID
 Dim objattTabOrder
 Dim objPI
 Dim x
 
 
 'Instantiate the Microsoft XMLDOM.
 Set objDom = server.CreateObject("Microsoft.XMLDOM")
 objDom.preserveWhiteSpace = True
 
 
 'Create your root element and append it to the XML document.
 Set objRoot = objDom.createElement("contact")
 objDom.appendChild objRoot
 
 
 'Iterate through the Form Collection of the Request Object.
 For x = 1 To Request.Form.Count
 
  'Check to see if "btn" is in the name of the form element.
  'If it is, then it is a button and we do not want to add it
  'to the XML document.
  If instr(1,Request.Form.Key(x),"btn") = 0 Then
 
   'Create an element, "field".
   Set objField = objDom.createElement("field")
 
   'Create an attribute, "id".
   Set objattID = objDom.createAttribute("id")
 
   'Set the value of the id attribute equal the the name of
   'the current form field.
   objattID.Text = Request.Form.Key(x)
 
   'The setAttributeNode method will append the id attribute
   'to the field element.
   objField.setAttributeNode objattID
 
   'Create another attribute, "taborder". This just orders the
   'elements.
   Set objattTabOrder = objDom.createAttribute("taborder")
 
   'Set the value of the taborder attribute.
   objattTabOrder.Text = x
 
   'Append the taborder attribute to the field element.
   objField.setAttributeNode objattTabOrder
 
   'Create a new element, "field_value".
   Set objFieldValue = objDom.createElement("field_value")
 
   'Set the value of the field_value element equal to
   'the value of the current field in the Form Collection.
   objFieldValue.Text = Request.Form(x)
 
   'Append the field element as a child of the root element.
   objRoot.appendChild objField
 
   'Append the field_value element as a child of the field elemnt.
   objField.appendChild objFieldValue
  End If
 Next 
 
 
 'Create the xml processing instruction.
 Set objPI = objDom.createProcessingInstruction("xml", "version='1.0'")
 
 'Append the processing instruction to the XML document.
 objDom.insertBefore objPI, objDom.childNodes(0)
 
 
 'Save the XML document.
 objDom.save strXMLFilePath & "\" & strFileName
 
 
 'Release all of your object references.
 Set objDom = Nothing
 Set objRoot = Nothing
 Set objField = Nothing
 Set objFieldValue = Nothing
 Set objattID = Nothing
 Set objattTabOrder = Nothing
 Set objPI = Nothing
End Function
 
 
'Do not break on an error.
On Error Resume Next
 
 
'Call the ConvertFormtoXML function, passing in the physical path to
'save the file to and the name that you wish to use for the file.
ConvertFormtoXML "c:","Contact.xml"
 
 
'Test to see if an error occurred, if so, let the user know.
'Otherwise, tell the user that the operation was successful.
If err.number <> 0 then
 Response.write("Errors occurred while saving your form submission.")
Else
 Response.write("Your form submission has been saved.")
End If
%>

If you use this code in your own applications, remember one thing, when the “ConvertFormtoXML” Function runs, if the XML file name specified already exists, it will be overwritten. I suggest dynamically creating random file names before calling the “ConvertFormtoXML” Function. That way you will never risk overwriting any valuable data.

The XML file that would be produced by this example would appear (something similar to) as follows:

Contact.xml

 
<?xml version="1.0" ?>
<contact>
 <field id="firstName" taborder="1">
  <field_value>Michael</field_value> 
 </field>
 <field id="lastName" taborder="2">
  <field_value>Qualls</field_value> 
 </field>
 <field id="address1" taborder="3">
  <field_value>2129 NW 27th St.</field_value> 
 </field>
 <field id="address2" taborder="4">
  <field_value /> 
 </field>
 <field id="phone" taborder="5">
  <field_value>4055253988</field_value> 
 </field>
 <field id="email" taborder="6">
  <field_value>michaelq@vertiscope.com</field_value> 
 </field>
</contact>

I would suggest copying the code for EnterContact.htm and processForm.asp to pages of the same name on your Web server and running the example. Make sure that you use a path and file name that work for your server. Examine the XML file when you are done.

If you’d like to play with the form, here’s a working demo for you.

The original post can be found here.