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.
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:
____________________________________________________
DOWNLOAD THE CODE.
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;
}
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;
}
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();
}
}
}
}
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)
}
}
}
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; }
}
}
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
- Related Videos
- Related Articles
- Ask / Related Q&A
- Javascript Feature: Read Xml String, Parse, And Set Elements To Values
- What You Need To Know About Ajax
- Introduction to Ajax
- Ajax-based Login Control Without Any Standard Database
- Asynchronous Javascript and Xml – Technology to Increase Website Interactivity!
- What is the Ajax Enabled Google Tool-kit?
- What is Ajax?
- On –server Ajax, a Paradigm Shift That Brings the Ajax Benefits to Enterprises




Tips for Avoiding a Bad Hosting Company - Your Choice to Make a Change
By: Colby Hodges | 30/12/2009You might not get lucky enough to have picked a great host on your first, or even second, attempt. Even after doing all the research we can a host doesn't end up as great as they seemed in pre-sales. What can you do if this happens to you? Fortunately you do have options, so don't decide to scrap your site just yet. Even if you're thinking your host has ruined all of your start-up buzz you can still bring your site back.
Cheap ffmpeg hosting for the Internet
By: Joey Smith | 30/12/2009Ffmpeg hosting is a new technology that is taking the world by storm and everyone seems to be interested in trying their hand at it. Sites online are are displaying ffmpeg web hosting as a powerful service and it is true.
Cheap web hosting for your site
By: Tom | 30/12/2009Along with a good domain name and a great looking website, in order to get your website seen you will need to have also found a good web hosting company. Put simply, web hosting allows your site to be visible on the World Wide Web, without it your site remains, well – invisible. Getting the right company to provide your cheap web hosting is something that far too many people leave to chance.
Cheap Web Hostings - Cheap Business Website Hosting Service Reviews
By: William Dean | 29/12/2009Check out to find free web hosting or cheap web hosting for your personal or business website. Business web hosting should be done more carefully as these web hosting services sometime doesn't deliver performance and enough bandwidth for your website.
Why choose a dedicated server?
By: Charlie | 29/12/2009A dedicated server will provide the solution to all your hosting requirements and is the answer to anyone who wants high reliability combined with total security and great performance. Having your own server means that you have total control over the applications that you host- without worrying about other account holders.
Se tem um website proteja o seu computador
By: nuno ribeiro | 29/12/2009Tal como o seu website, o seu computador deve ser monitorizado regularmente à procura de eventuais brechas de segurança. Muitos websites estão infectados com trojans (cavalos de tróia), iframe injections ou mesmo vírus. Se suspeita que o seu site foi apanhado por alguma destas ocorrências é altura ideal para fazer uma verificação completa ao seu próprio computador.
O problema do “Overselling”
By: nuno ribeiro | 29/12/2009“Overselling“, termo utilizado para definir, na indústria do alojamento web, o acto de uma empresa em fornecer serviços e recursos em que, se todos os seus clientes usufruíssem da totalidade dos serviços anunciados criaria uma situação insustentável levando a falhas críticas no servidor. Normalmente o “overselling” diz respeito ao uso de espaço em disco e transferência de dados mensal.
What is The Lifeblood of Internet?
By: Mark Spenser | 29/12/2009The following article gives details on the ecommerce websites and the way in which they are essential for the overall money making in the whole wide world. In reality, it was a path breaking revolution that ecommerce website brought into the world of World Wide Web. Ever since its inception, Ecommerce has been successful in bringing billions of dollars to all the wholesalers and retailers all across the world and hence, making it a lifeline for several small businessmen for earning their living.
Php 101: Php Finding Keys Within Sessions Using Isset() And_Key_Exists()
By: Rob Guida | 24/02/2009 | ProgrammingThe isset function is a staple utility of PHP to make sure sessions variables exist before accessing them. Unless you are familiar with session variables, even after reading about them on php.net, this lesson will help you gain a better understanding on how to check the existence of a session key.