Ajax Read Xml Response Find Specific Node

expanded

collapsed

There is a lot to say when it comes to AJAX! If You have read the commodity "Integrating Ajax into traditional IBM Lotus Domino Web applications" (http://www-x.lotus.com/ldd/ddwiki.nsf/dx/Integrating_Ajax_into_traditional_IBM_Lotus_Domino_Web_applications) You will know how to use the Ajax response when information technology is supplied as a TEXT, merely Ajax is more powerful than that. What does the abbrevation Ajax stand for? Asynchronous Java(script) And XML! To fully utilize the capacity of Ajax, then we have to empathise how to process the response every bit XML.

There is a lot to say when it comes to AJAX!

I will have You through one of the Ajax calls I did in a sales application I did for a customer before this year and cutting out unnecessary bits and pieces from the code. The sales application had 1 main document containing data most the customer and general stuff, and then the user added one product document for each production that should be included in the offer. Each product document could have different disbelieve values, merely in the main document they wanted a summary to be displayed of the total gross, net and discount values for the whole offer.

So, each time I wanted to update this summary, I made an Ajax telephone call to get the values. Here is the telephone call for retreiving the summary:

var xmlHttp = null;
function initAJAX()              
{
              
   render new ajaxRequest();
}
function ajaxRequest()              
{
              
    //'IE
     var localXmlHttp = cypher;
    endeavor {
      localXmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        localXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
        localXmlHttp = imitation;
      }
    }
    //All the balance
    if (!localXmlHttp && typeof XMLHttpRequest != 'undefined') {
          localXmlHttp = new XMLHttpRequest();
    }
              
    return localXmlHttp;
}
role getSummary() {
 //alert('start');
 var docid = document.getElementById('DocID').value;
 var sURL = '';
 if (docid == '') {
  return faux;
 }
 sURL = getServerName() + '/' + dbPath + '/(ajaxGetSPASummary)?OpenAgent&id=' + docid;
 endeavor {
  if (xmlHttp == null) {
   xmlHttp = initAJAX();
  }
  var d = new Date();
  //Annotation THIS!  By calculation a date/time stamp to the ajax call will make the browser to ignore any cached result!
  //This will make every URL unique, and no cache being used...
  xmlHttp.open("Go",sURL + '&dummy=' + d.getTime(),true);
  xmlHttp.onreadystatechange = summarydone
  xmlHttp.send(null);
 }
 take hold of(due east) {
  alarm(e.message);
 }
}
function summarydone() {
 // This function could be embedded directly at the onreadystatechange in a higher place, but I recollect              
 // that doing like this makes the code more readable.              
 if (typeof(xmlHttp) !='undefined') {
  if (xmlHttp.readyState==4) {
   if (xmlHttp.status!=200) {
    alert('Mistake checking for status : ' + xmlHttp.condition);
   } else {
    summaryFinalize();
   }
  }
 }
}

It would trigger an agent called 'ajaxGetSPASummary'. Here is the agent:

 On Error Goto errorhandler

 Dim session As New NotesSession

 Dim db Equally NotesDatabase
 Dim doc As NotesDocument
 Dim strQS As String
 Dim strXML As String
 Dim sFormula Equally String
 Dim vEval As Variant
 Dim dblGrossSales Equally Double
 Dim dblNetSales As Double
 Dim dblDiscount As Double
              
 Set db = session.CurrentDatabase
 Gear up doc = session.DocumentContext
 strQS = doc.Query_String_Decoded(0)
 strQS = Strright(strQS,"&id=")
 strQS = Strleft(strQS,"&")
              
 If strQS = "" And so
  Exit Sub
 End If

 sFormula = |@Sum(@DbLookup("":"NoCache";"":"";"(LookupProductsByDocId)";"| + strQS + |";"GrossSales"))|

 vEval = Evaluate(sFormula)
 If Isempty(vEval) Then
  dblGrossSales = 0
 Else
  dblGrossSales = CDbl(vEval(0))
 End If

 sFormula = |@Sum(@DbLookup("":"NoCache";"":"";"(LookupProductsByDocId)";"| + strQS + |";"NetSales"))|

 vEval = Evaluate(sFormula)
 If Isempty(vEval) Then
  dblNetSales = 0
 Else
  dblNetSales = CDbl(vEval(0))
 Stop If

 dblDiscount = Round((dblGrossSales - dblNetSales) / dblGrossSales,4)*100

 strXML = |<?xml version='one.0' encoding='ISO-8859-1'?>| & Chr$(13)

 strXML = strXML & |<summary>|&Chr$(13)
 strXML = strXML & |<docid>| & strQS & |</docid>| & Chr$(13)
 strXML = strXML & |<gross>| & Format$(dblGrossSales,"0") & |</gross>| & Chr$(thirteen)
 strXML = strXML & |<cyberspace>| & Format$(dblNetSales,"0") & |</cyberspace>| & Chr$(13)
 strXML = strXML & |<discount>| & Format$(dblDiscount,"0") & |</discount>| & Chr$(thirteen)
 strXML = strXML & |</summary| & Chr$(13)

agt_done:

              
 Print |Content-Type:text/xml| & Chr$(xiii) ' Important! This must exist the first printed line in the agent!
 Print strXML
 Get out Sub

errorhandler:

 Call LogError()
 strXML = |<?xml version="i.0" ?>| & Chr$(13)
 strXML = strXML & |<product>|&Chr$(thirteen)
 strXML = strXML & |<mistake code="| & Cstr(Err) & |" line="| & Cstr(Erl) & |">| & Error$ & |</error>| & Chr$(13)              
 strXML = strXML & |</product>|
              
 Resume agt_done

Note two things in the agent:
1. The result of the agent is printed in XML format and we override the default creation of HTML-tags that all Domino agents do past printing the content type with

Print |Content-Type:text/xml| & Chr$(thirteen)

This line must be the start printed line in the agent or Domino will produce the HTML tags!

2. The error is printed in XML format with attributes. I do not recommend using attributes when working with XML but I'grand but doing it here for demonstration purposes.

So, when the amanuensis is washed, the JavaScript volition call a JavaScript function called 'summaryFinalize()'. The global JavaScript variable/object chosen xmlHttp holds the effect from the agent. You tin can now examine the XML-output past alerting the responsetext by:

 alarm(xmlHttp.responseText);

Only since the output is not easy to read, we demand to procedure the XML. Allow's start with grabbing the showtime element in the XML-file:

var root = xmlHttp.responseXML.getElementsByTagName('summary').detail(0);

If we don't get a root object then nosotros can not keep, therefore nosotros add errorhandling:

if (root == null) {
 //Add together alarm or anything to inform user that something bad has happened!!
 return;
}

Now nosotros are ready to step through all the elements in the XML file. For each node, we examine the proper name of the node and in a JavaScript switch() we will practice differently depending on which node we are currently processing. For each node, we are press out the upshot in a respective HTML field on the form. Similar, the 'gross' element will exist written to a HTML field called 'dspGrossSales etc...

 for (var iNode = 0; iNode < root.childNodes.length; iNode++) {
  var node = root.childNodes.item(iNode);
              
  switch(node.nodeName) {
  case 'error':
   var ecode = node.getAttribute("code"); // JavaScript is case sensitive! It should be '.getAttribute()' and Non '.GetAttribute()'
   var eline = node.getAttribute("line");
   var etext = node.firstChild.nodeValue;
   var strHtml = '<div grade="error"><h1>An fault occured</h1><p>Unable to process the request due to the following error:</p><p class="errortext">';
   strHtml += 'Errorcode: ' + ecode + '<br />Errorline: ' + eline + '<br />Description: ' + etext + '<br /></p></div>';
   var objError = document.getElementById('Message');
   If (objError != aught) {
    objError.innerHTML = strHtml;
   }
   break;
  case 'gross':
   obj = document.getElementById('dspGrossSales');
   if (obj != null) {
    obj.value = node.firstChild.nodeValue;
   }
   break;
  instance 'internet':
   obj = certificate.getElementById('dspNetSales');
   if (obj != null) {
    obj.value = node.firstChild.nodeValue;
   }
   break;
  case 'disbelieve':
   obj = document.getElementById('dspDiscount');
   if (obj != zip) {
    obj.value = node.firstChild.nodeValue;
   }
   break;
  }
 }              

Here is the whole JavaScript role 'summaryFinalize()':

office summaryFinalize() {
 //alert(xmlHttp.responseText);
 var root = xmlHttp.responseXML.getElementsByTagName('summary').detail(0);
 var obj;
              
 if (root == null) {
  return;
 }
 for (var iNode = 0; iNode < root.childNodes.length; iNode++) {
  var node = root.childNodes.item(iNode);
              
  switch(node.nodeName) {
  case 'error':
   var ecode = node.getAttribute("code");
   var eline = node.getAttribute("line");
   var etext = node.firstChild.nodeValue;
   var strHtml = '<div class="error"><h1>An error occured</h1><p>Unable to procedure the request due to the following fault:</p><p class="errortext">';
   strHtml += 'Errorcode: ' + ecode + '<br />Errorline: ' + eline + '<br />Description: ' + etext + '<br /></p></div>';
   var objError = document.getElementById('Message');
   If (objError != null) {
    objError.innerHTML = strHtml;
   }
   break;
  example 'gross':
   obj = certificate.getElementById('dspGrossSales');
   if (obj != null) {
    obj.value = node.firstChild.nodeValue;
   }
   break;
  case 'internet':
   obj = document.getElementById('dspNetSales');
   if (obj != null) {
    obj.value = node.firstChild.nodeValue;
   }
   intermission;
  case 'discount':
   obj = document.getElementById('dspDiscount');
   if (obj != nothing) {
    obj.value = node.firstChild.nodeValue;
   }
   interruption;
  }
 }              
}

At present, what if the XML file is more complicated that this? My XML file merely contains 1 level of nodes. What if a node contains subnodes which contains subnodes etc...?
So You have to make a for loop inside the for loop... This is nothing I'm covering in this commodity but I think that once You understand the XML format, it volition non be whatever issues for You to walk through the nodes.

greshamdereddeedly.blogspot.com

Source: https://ds-infolib.hcltechsw.com/ldd/ddwiki.nsf/dx/Using_XML_response_from_Ajax_call_in_Lotus_Domino_Web_applications

0 Response to "Ajax Read Xml Response Find Specific Node"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel