Javascript Feature: Read Xml String, Parse, And Set Elements To Values
Author: Rob Guida
JavaScript Feature: Read XML String, Parse, and Set Elements to Values
Written by: Robert Guida, guidaMedia.com, ©2009.
Who is this for?
Getting a fully functional script that actually reads in XML, parses
it, and then sets element values is not easy to find on the Web. I
searched for hours, but was only able to find bits and pieces to put
together a function. So if you are looking to have a PHP script create
an XML document filled with variables and HTML, then this code is for
you.
What are all the files I need to evaluate this code?
The parts involved in this example code are a PHP file, "AJAX.php",
and an HTML file, "AJAX.htm", with a few JavaScript functions.
- The PHP file creates the XML string. Note: all values should be URL encoded to ensure HTML strings do not break the code.
- The HTML file provides the elements, and the following JavaScript to render the XML.
- JavaScript function to create the XMLHttpRequest: get_oXMLHTTP().
- JavaScript function to call the PHP file and retreive the responseText: getAJAXContent_XML().
- JavaScript function to create an XML object from the responseText: loadXMLString().
- JavaScript function to run through the XML object and set the elements to the values: setElementValues().
- JavaScript function that decode the URL encryption that is put on all the nodes of the XML object.
PHP and JavaScript Coordination
There is some coordination between the PHP file, and the JavaScript
funciton setElementValues(). The tags that hold the key information in
the XML document are "formID" and "formVal". More appropriate names
would be elementID and elementValue, since these nodes cooresponde to
the elements. The setElementValues() function gets the values of these
two nodes, and based on the value for formID, that element in the HTML
document will have its innerHTML set to the value found in the formVal
node. If element name does not match the formID value, then the value
is read, but never set.
Demo and Download
O.K. That is a lengthy intro, and if you are like me you just want
the code, and to see an example. If you feel like you need some
explanation, then you RTFM (Read The Freaking Manual). So let's get to
the good stuff... the example. Below is some HTML with a few element
tags. Click the "Run AJAX XML Script" and see what happens. After that,
down load the script, and open it in your editor.
This form will not work in this article. Please use the links at the bottom of the article to use the function examples.
___________________________________________________
E-Mail Receipt
To:
From:
Subject:
Message:
____________________________________________________
How does it work?
- Create an XMLHttpRequest Object
The function "get_oXMLHTTP()" is a standardized script that you can get
from W3C.org. It simply tests the browser type, and based upon that
creates a XMLHttp object and returns it to the caller. We will go over
the caller towards the end. function get_oXMLHTTP(){
var output = null;
try{// Firefox, Opera 8.0+, Safari
output = new XMLHttpRequest();
}catch(e){ // Internet Explorer
try{
output = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
output = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return output;
}
- Call the PHP file, and retrieve the responseText
The function "getAJAXContent_XML()" is a standardized script that you
can get from W3C.org. It simply calls the PHP and retrieves the XML
string. What is different is that it uses loadXMLString() to load the
XML sting into an object "XMLDoc", and then sets the document elements
(Marked in red). function getAJAXContent_XML(objHTTP, url){
if (objHTTP != null){
objHTTP.open("POST", url, true);
objHTTP.send(null);
objHTTP.onreadystatechange = function(){
if(objHTTP.readyState == 4){
loadXMLString(objHTTP.responseText);
setElementValues();
}
}
}
}
- Create an XML Object from string
The function "get_oXMLHTTP()" is a standardized sceipt that you can get
from W3C.org. It simply tests the browser type, and based upon that it
loads the XML string into XMLDoc. Where the Microsoft XMLDOM just loads
the string, the non IE browsers creates a DOMParser, and then has the
object to "parseFromString", which is pretty litteral in its name. So
no need for further explaination. Just notice that the function needs
to know the type, and that is where "text/xml" is key in transfering
the string into an actual XML object. Up to this point, the string is
only a string properly formated as an XML document. function
loadXMLString(xmlData) {
try { //Internet Explorer
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlData);
}catch(e){ //Firefox et. all
try {
parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlData, "text/xml");
}catch(e){
alert(e.message)
}
}
}
- Run through the XML object and set the document element innerHTML attribute
This function uses the XMLDoc object loaded via loadXMLString().
Another object is created, "oRV", to hold the entire node that is named
"elementValues". Another object, "oV", is created to hold the child
node list. The node list is made up of children using the "record" tag.
Looping through the child node list we get the child nodes for "formID"
and "formVal". The values are decoded. If the document element exists,
then it sets that document element to the formVal pulled from the XML
object. function setElementValues(){
var oRV = xmlDoc.getElementsByTagName("elementValues");
var oV = oRV[0].childNodes;
var formID = "";
var value = "";
for (i = 0; i < oV.length; i++){
oFormID = oV[i].getElementsByTagName("formID");
oFormVal = oV[i].getElementsByTagName("formVal");
formID = URLDecode(oFormID[0].text);
formVal = URLDecode(oFormVal[0].text);
if(document.getElementById(formID)){ document.getElementById(formID)[removed] = formVal; }
}
}
- Decoding the URL encrypted node values
The function "URLDecode()" simply uses the escape() JavaScript
function, and translates the URL encoded content into a HTML compatible
string. The only thing not escaped from the PHP urlencode are the plus
"+". Using the JavaScript function replace(), the string is quickly
cleaned of any visible "+" signs. Make sure you use proper HTML codes
for the "+" sign, which is "+". function URLDecode(val){
var output = "";
output = unescape(val);
output = output.replace(/\+/g, " ");
return output;
}
If you have any questions, please do not hesitate to contact me, click here. I will do my best to get back to you promptly.
Take care and good luck in your endevours.
Rob, 2009
About the Author:
Mr. Guida develops accounting systems, property management systems,
Intranets for corporate WANs, R&D Procurement, Budget and Fiscal
Management systems for the Federal Government, and custom content
management systems.
As well as an accomplished developer, Mr. Guida enjoys sharing his
knowledge by writing articles. Articles include helping businesses make
good decisions on there next intranet project, by helping them
understand what they should expect from their programmers. Other
articles are geared toward new programmers, helping them attain a more
thorough understanding of development through lessons, and how-to-s.
Article Source: ArticlesBase.com - Javascript Feature: Read Xml String, Parse, And Set Elements To Values