Any way has any one come across anything like this?
SOLVED: Detect & add ID's to XML loaded via AJAX?
Moderator: General Moderators
- JAB Creations
- DevNet Resident
- Posts: 2341
- Joined: Thu Jan 13, 2005 6:44 pm
- Location: Sarasota Florida
- Contact:
SOLVED: Detect & add ID's to XML loaded via AJAX?
I'm curious if anyone is aware of any existing function already written that will go through the contents of code loaded via innerHTML and make the DOM aware of any/all/specific/etc ID's present in what is otherwise a blind dump? Obviously the function would be called on a certain state...though all I keep seeing are references to certain JavaScript frameworks that I won't mention them as I typically search with -that_framework_here. 
Any way has any one come across anything like this?
Any way has any one come across anything like this?
Last edited by JAB Creations on Thu Mar 05, 2009 9:46 pm, edited 1 time in total.
- JAB Creations
- DevNet Resident
- Posts: 2341
- Joined: Thu Jan 13, 2005 6:44 pm
- Location: Sarasota Florida
- Contact:
Re: Function to detect and add ID's from innerHTML and AJAX?
Hm....looks like I've been using a hammer instead of a lock pick. responseXML looks like it may be useful for this...I'll post more after I get something working, hopefully before I lose consciousness. 
- JAB Creations
- DevNet Resident
- Posts: 2341
- Joined: Thu Jan 13, 2005 6:44 pm
- Location: Sarasota Florida
- Contact:
Re: Function to detect and add ID's from innerHTML and AJAX?
Well the closest I've found so far is the following page...
http://www.in3d.eu/in3d_Programming/AJA ... seXML.html
I have had some initial success today...
...this is after I added a divisible element as the first element (commenting out the XML element declaration) in the PHP file's client output.
Right now I'm reading...
http://www.stylusstudio.com/xmldev/2002 ... 81630.html
...as it seems getElementById is not supported by default in the current test case.
This is pretty major as it blows the door wide open on an issue I want to address in version 3.0 of my site though it also let's me address some more moderate issues in the more immediate term. I will post a minimal test case once I have everything working smoothly for those reading following this or later reading it as an archive.
http://www.in3d.eu/in3d_Programming/AJA ... seXML.html
I have had some initial success today...
Code: Select all
alert(xmlDoc.getElementsByTagName('div')[0].firstChild.nodeValue);Right now I'm reading...
http://www.stylusstudio.com/xmldev/2002 ... 81630.html
...as it seems getElementById is not supported by default in the current test case.
This is pretty major as it blows the door wide open on an issue I want to address in version 3.0 of my site though it also let's me address some more moderate issues in the more immediate term. I will post a minimal test case once I have everything working smoothly for those reading following this or later reading it as an archive.
- JAB Creations
- DevNet Resident
- Posts: 2341
- Joined: Thu Jan 13, 2005 6:44 pm
- Location: Sarasota Florida
- Contact:
Re: Function to detect and add ID's from innerHTML and AJAX?
Except for a half hour meal/anime break I've been working on cleaning up Kostas Zotos's demo script that I mentioned above. Minimizing the code has been one of my priorities and dealing with, 'Hey I figured it out but won't post working example of my code' exclamations all day have been my biggest headache.
Any way I'm now trying to get access to the ID as loading the content properly seems to work. Below are the pages and a test image I'm using so hopefully this will work as a nice basis to get the ID issue working. This code works in Firefox 3 and Opera 10 however it strangely doesn't work in Safari 4 and naturally doesn't work in IE8. I'll deal with browser specific issues after I get the Id bit working or if someone is able to post something helpful first. I'm just happy at the moment to be this far along...
index.html
XMLHttpRequest_responseXML.php
XMLHttpRequest_responseXML.js
malia-fallen_angel.jpg

Any way I'm now trying to get access to the ID as loading the content properly seems to work. Below are the pages and a test image I'm using so hopefully this will work as a nice basis to get the ID issue working. This code works in Firefox 3 and Opera 10 however it strangely doesn't work in Safari 4 and naturally doesn't work in IE8. I'll deal with browser specific issues after I get the Id bit working or if someone is able to post something helpful first. I'm just happy at the moment to be this far along...
index.html
Code: Select all
<?php header("content-type:application/xhtml+xml;"); echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><title>XMLHttpRequest: responseXML Example</title><meta name="description" content="in3d.eu - PROGRAMMING by Kostas Zotos. XMLHttpRequest: responseXML Example. Download the Full working example: Html, JavaScript and the Server Script (PHP)" /><meta name="Keywords" content="XML HttpRequest, responseXML, AJAX, php, Dynamic web pages, download, complete, example" /><meta name="robots" content="Index" /><style type="text/css">body, html {background-color: #456978; color:#dee; font-family: Verdana;}a:link, a:visited {color:#234; font-family: Verdana;}a:focus, a:hover, a:active {color:#fff;}img.imgborder {border: #f0f solid 30px;}span.test {background-color: #ff0; color: #000;}</style><script language="javascript" type="text/javascript" src="XMLHttpRequest_responseXML.js"></script><script type="text/javascript">//<![CDATA[function change(id, newClass) {var identity=document.getElementById(id); identity.className=newClass;} function getElementByIdMXL(the_node,the_id){ //get all the tags in the doc var node_tags = the_node.getElementsByTagName('*'); for (i=0;i<node_tags.length;i++) { //is there an id attribute? if (node_tags[i].hasAttribute('id')) { //if there is, test its value if (node_tags[i].getAttribute('id') == the_id) { //and return it if it matches return node_tags[i]; } else { return '??'; } } } return false;} function getElementByIdXML(node,id){ //var nodes = node.getElementsByTagName('*'); //var nodes = xmlDoc.getElementsByTagName('*');var nodes = document.getElementById('ajax_here').getElementsByTagName('*'); for (var i=0;i<nodes.length;i++) { if (nodes[i].hasAttribute('id')) { if (nodes[i].getAttribute('id') == id) { return nodes[i]; //matching id } } } return false;}//]]></script></head> <body> <div style="background:#487987; border:1px solid #112233; margin: auto; padding:10px; width:770px;"> <div id="ajax_here"></div> <div><a href="javascript:alert(getElementByIdXML('xmlDoc','test_span').getAttribute('title'))">Alert AJAX span element title.</a></div><div><a href="javascript:change(getElementByIdXML('xmlDoc','test_span'), 'test')">Change class of 'test_span' to class 'test'.</a></div> <h3>XMLHttpRequest: responseXML Example</h3> <div><span style=" font:13px/12pt verdana; letter-spacing:1px">Complete Example demonstrating the use of XML HttpRequest's "responseXML"</span></div><div><span style="color:#334455; font:8pt verdana; letter-spacing:1px" >( By Kostas Zotos 8/2008 ) </span></div> <form><textarea name="CellData" id="CellData" style="background:#659aa7; border:1px solid #234; height:110px; margin: 2px auto 2px auto; width: 100%;">This text will be replaced by the XML sent by PHP... (Click the button to send some data to PHP..)</textarea> <div><input type="button" style="background:#659aa7; border:1px solid #234; height:25px; margin: 2px auto 2px auto; width: 100%;" value="Click to send the current Date and Time" onclick="SendData(new Date())" /></div></form> </div> </body></html>Code: Select all
<?php
header('Content-Type: text/xml');
header ('Cache-Control: no-cache');
header ('Cache-Control: no-store' , false); // false => this header not override the previous similar header
//-------------- If want to read an existing .xml file -------------------------
// $XmlFile="Data.xml";
/*// Using the DOM Functions
$doc=new DOMDocument();
$doc->formatOutput=true;
$doc->load($XmlFile);
// echo $doc->saveXML(); // Returns the xml as string
*/
// OR: Directly open the file:
// readfile($XmlFile); // Output directly the given file to browser
//-------------- If want to read an existing .xml file (END) -----------------
if (isset($_GET['Date'])){
$Date=trim($_GET['Date']); // Reads the GET request "Date" variable (removes leading/trailing whitespaces)
$Date=strip_tags($Date); // Removes possible html and php tags (to prevent possible malicious code)
} else {
$Date=@date("l, d F Y ( H:i:s A )");
}
// Manually create a string representation of a new xml document
// Inserting also the GET variable
/*<?xml version="1.0" encoding="UTF-8"?>*/
$xmlStr='<div xmlns="http://www.w3.org/1999/xhtml" id="response">1234
<div>aa<span class="test" id="test_span" title="TITLE TEXT HERE!">bb</span></div>
<div><img alt="test image" class="imgborder" src="malia-fallen_angel.jpg" title="test image" /></div>
<data id="ajax_id1"><Date id="ajax_id2">'.$Date.'</Date><ip>'.$_SERVER['REMOTE_ADDR'].'</ip></data>
</div>
';
echo $xmlStr;
?>Code: Select all
<?php header("content-type: application/javascript");?> var xmlhttp;function SendData(Arg){ xmlhttp=null; var Url='XMLHttpRequest_responseXML.php';// THE SERVER SCRIPT TO HANDLE THE REQUEST if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest();// For all modern browsers } else if (window.ActiveXObject) { xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');// For (older) IE } if (xmlhttp!=null) { xmlhttp.onreadystatechange=onStateChange; Url=Url+'?Date='+escape(Arg)+'&NoCache='+new Date().getTime(); // '&NoCache' => Append the timestamp to avoid cashing // Also escape the input argument (Arg) to properly url-encode the characters (to be sure) xmlhttp.open('GET', Url, true);// (httpMethod, URL, asynchronous) // xmlhttp.overrideMimeType('text/xml'); xmlhttp.send(null); /* // How to send a POST request xmlhttp.open('POST', Url, true); // (httpMethod, URL, asynchronous) xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); xmlhttp.send( 'Date=' + escape(Arg) ); */ } else { alert('The XMLHttpRequest not supported'); }} function onStateChange(){ if (xmlhttp.readyState==4) { if (xmlhttp.status==200) { var xmlDoc=xmlhttp.responseXML;// 'xmlDoc' the returned xml object var DateNode=xmlDoc.getElementsByTagName('Date')[0].firstChild.nodeValue // The <Date> element's node value (the sent date) var Xml2String // Convert the xml to string just to display it if (xmlDoc.xml) {Xml2String=xmlDoc.xml}// Converts the xml object to string ( For IE) else {Xml2String= new XMLSerializer().serializeToString(xmlDoc);}// Converts the xml object to string (For rest browsers, mozilla, etc) //alert(Xml2String); //alert(xmlhttp.responseText); document.getElementById('CellData').value=Xml2String; //alert(xmlDoc.getElementsByTagName('div')[0].firstChild.nodeValue); document.getElementById('ajax_here').appendChild(xmlDoc.getElementsByTagName('div')[0]); //document.getElementById('ajax_here').appendChild(document.importNode(xmlDoc.getElementsByTagName('div')[0],true)); //document.getElementById('ajax_here').innerHTML = xmlDoc.getElementsByTagName('div')[0]; //alert(xmlDoc.getElementById('response').nodeValue); } else { //ajax_here //document.getElementById('ajax_here').appendChild(element_new); document.getElementById('ajax_here').appendChild(Xml2String); //alert('statusText: ' + xmlhttp.statusText + '\nHTTP status code: ' + xmlhttp.status); }// End of: if (xmlhttp.status==200) }}
- JAB Creations
- DevNet Resident
- Posts: 2341
- Joined: Thu Jan 13, 2005 6:44 pm
- Location: Sarasota Florida
- Contact:
Re: Function to detect and add ID's from innerHTML and AJAX?
Here is an update and everything seems to be working fine except for Internet Explorer naturally (to test in IE comment out the media type or change to application/xml instead). I haven't changed the image I'm using so if you want to test it out feel free to use the one in my previous post.
I'm testing this in IE8 RC1. I've been trying to figure out how to implement a solution I came across on this page...
http://www.alistapart.com/articles/cros ... rscripting
...besides IE this works beautifully! Any help getting IE to work would be greatly appreciated since I've already done the bulk of the work here.
Either way I hope to get this working in all AJAX capable browsers/versions. If I can get a little help with IE then I'll be more then happy to provide fallback for IE5, 5.5, and 6.0 since they don't support responseXML like IE7+ once I get IE8 working. 
index.html
XMLHttpRequest_responseXML.js
XMLHttpRequest_responseXML.php
I'm testing this in IE8 RC1. I've been trying to figure out how to implement a solution I came across on this page...
http://www.alistapart.com/articles/cros ... rscripting
...besides IE this works beautifully! Any help getting IE to work would be greatly appreciated since I've already done the bulk of the work here.
index.html
Code: Select all
<?php header("content-type:application/xhtml+xml;"); echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><title>XMLHttpRequest: responseXML Example</title><meta name="description" content="in3d.eu - PROGRAMMING by Kostas Zotos. XMLHttpRequest: responseXML Example. Download the Full working example: Html, JavaScript and the Server Script (PHP)" /><meta name="Keywords" content="XML HttpRequest, responseXML, AJAX, php, Dynamic web pages, download, complete, example" /><meta name="robots" content="Index" /><style type="text/css">body, html {background-color: #456978; color:#dee; font-family: Verdana;}a:link, a:visited {color:#234; font-family: Verdana;}a:focus, a:hover, a:active {color:#fff;}div.test {background-color: #f00;}img.imgborder {border: #f0f solid 30px;}img.test {border: #0ff dotted 30px;}span.test {background-color: #ff0; color: #000;}</style><script language="javascript" type="text/javascript" src="XMLHttpRequest_responseXML.js"></script><script type="text/javascript">//<![CDATA[function change(id, newClass) {var identity=document.getElementById(id); identity.className=newClass;} function getElementByIdMXL(the_node,the_id){ //get all the tags in the doc var node_tags = the_node.getElementsByTagName('*'); for (i=0;i<node_tags.length;i++) { //is there an id attribute? if (node_tags[i].hasAttribute('id')) { //if there is, test its value if (node_tags[i].getAttribute('id') == the_id) { //and return it if it matches return node_tags[i]; } else { return '??'; } } } return false;} function getElementByIdXML(node,id){ //var nodes = node.getElementsByTagName('*'); //var nodes = xmlDoc.getElementsByTagName('*');var nodes = document.getElementById('ajax_here').getElementsByTagName('*'); for (var i=0;i<nodes.length;i++) { if (nodes[i].hasAttribute('id')) { if (nodes[i].getAttribute('id') == id) { return nodes[i]; //matching id } } } return false;}//]]></script></head> <body> <div style="background:#487987; border:1px solid #112233; margin: auto; padding:10px; width:770px;"> <div id="ajax_here"></div> <div><a href="javascript:alert(getElementByIdXML('xmlDoc','test_span').getAttribute('title'))">Alert AJAX span element title.</a></div><div><a href="javascript:alert(getElementByIdXML('xmlDoc','response').getAttribute('class'))">Alert AJAX span element class.</a></div><div><span onclick="getElementByIdXML('xmlDoc','response').className='test';return false;">Change class of 'test_span' to class 'test'.</span></div><div><span onclick="change('response','test');" style="color: #ff0; font-size: 22px;">Change class of 'test_span' to class 'test1'.</span></div><div><span onclick="change('response','test'); change('img_test','test');" style="color: #ff0; font-size: 22px;">Change class of 'test_span' to class 'test2'.</span></div> <h3>XMLHttpRequest: responseXML Example</h3> <div><span style=" font:13px/12pt verdana; letter-spacing:1px">Complete Example demonstrating the use of XML HttpRequest's "responseXML"</span></div><div><span style="color:#334455; font:8pt verdana; letter-spacing:1px" >( By Kostas Zotos 8/2008 ) </span></div> <form><textarea name="CellData" id="CellData" style="background:#659aa7; border:1px solid #234; height:110px; margin: 2px auto 2px auto; width: 100%;">This text will be replaced by the XML sent by PHP... (Click the button to send some data to PHP..)</textarea> <div><input type="button" style="background:#659aa7; border:1px solid #234; height:25px; margin: 2px auto 2px auto; width: 100%;" value="Click to send the current Date and Time" onclick="SendData(new Date())" /></div></form> </div> </body></html>Code: Select all
<?php header("content-type: application/javascript");?> var xmlhttp;function SendData(Arg){ xmlhttp=null; var Url='XMLHttpRequest_responseXML.php';// THE SERVER SCRIPT TO HANDLE THE REQUEST if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest();// For all modern browsers } else if (window.ActiveXObject) { xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');// For (older) IE } if (xmlhttp!=null) { xmlhttp.onreadystatechange=onStateChange; Url=Url+'?Date='+escape(Arg)+'&NoCache='+new Date().getTime(); // '&NoCache' => Append the timestamp to avoid cashing // Also escape the input argument (Arg) to properly url-encode the characters (to be sure) xmlhttp.open('GET', Url, true);// (httpMethod, URL, asynchronous) // xmlhttp.overrideMimeType('text/xml'); xmlhttp.send(null); /* // How to send a POST request xmlhttp.open('POST', Url, true); // (httpMethod, URL, asynchronous) xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); xmlhttp.send( 'Date=' + escape(Arg) ); */ } else { alert('The XMLHttpRequest not supported'); }} function onStateChange(){ if (xmlhttp.readyState==4) { if (xmlhttp.status==200) { var xmlDoc=xmlhttp.responseXML;// 'xmlDoc' the returned xml object var DateNode=xmlDoc.getElementsByTagName('Date')[0].firstChild.nodeValue // The <Date> element's node value (the sent date) var Xml2String // Convert the xml to string just to display it if (xmlDoc.xml) {Xml2String=xmlDoc.xml}// Converts the xml object to string ( For IE) else {Xml2String= new XMLSerializer().serializeToString(xmlDoc);}// Converts the xml object to string (For rest browsers, mozilla, etc) //alert(Xml2String); //alert(xmlhttp.responseText); document.getElementById('CellData').value=Xml2String; //alert(xmlDoc.getElementsByTagName('div')[0].firstChild.nodeValue); //document.getElementById('ajax_here').appendChild(xmlDoc.getElementsByTagName('div')[0]); //works fine, commented out to get IE to work! document.getElementById('ajax_here').appendChild(document.importNode(xmlDoc.getElementsByTagName('div')[0],true)); } else { //ajax_here //document.getElementById('ajax_here').appendChild(element_new); document.getElementById('ajax_here').appendChild(Xml2String); //alert('statusText: ' + xmlhttp.statusText + '\nHTTP status code: ' + xmlhttp.status); }// End of: if (xmlhttp.status==200) }}Code: Select all
<?php
header('Content-Type: text/xml');
header ('Cache-Control: no-cache');
header ('Cache-Control: no-store' , false); // false => this header not override the previous similar header
//-------------- If want to read an existing .xml file -------------------------
// $XmlFile="Data.xml";
/*// Using the DOM Functions
$doc=new DOMDocument();
$doc->formatOutput=true;
$doc->load($XmlFile);
// echo $doc->saveXML(); // Returns the xml as string
*/
// OR: Directly open the file:
// readfile($XmlFile); // Output directly the given file to browser
//-------------- If want to read an existing .xml file (END) -----------------
if (isset($_GET['Date'])){
$Date=trim($_GET['Date']); // Reads the GET request "Date" variable (removes leading/trailing whitespaces)
$Date=strip_tags($Date); // Removes possible html and php tags (to prevent possible malicious code)
} else {
$Date=@date("l, d F Y ( H:i:s A )");
}
// Manually create a string representation of a new xml document
// Inserting also the GET variable
/*<?xml version="1.0" encoding="UTF-8"?>*/
$xmlStr='<div xmlns="http://www.w3.org/1999/xhtml" class="test579" id="response">1234
<div>aa<span class="test" id="test_span" title="TITLE TEXT HERE!">bb</span></div>
<div><img alt="test image" class="imgborder" id="img_test" src="malia-fallen_angel.jpg" title="test image" /></div>
<data id="ajax_id1"><Date id="ajax_id2">'.$Date.'</Date><ip>'.$_SERVER['REMOTE_ADDR'].'</ip></data>
</div>
';
echo $xmlStr;
?>Re: Function to detect and add ID's from innerHTML and AJAX?
Don't you just love the forum posts where you talk to yourself?
- JAB Creations
- DevNet Resident
- Posts: 2341
- Joined: Thu Jan 13, 2005 6:44 pm
- Location: Sarasota Florida
- Contact:
Re: Function to detect and add ID's from innerHTML and AJAX?
I love it even more when I get replies.
My only beef really is that all pages I find where people apparently figure things out...they don't post any code! At least others can learn from what I'm posting...I'm not just trying to find an answer...I'm trying to make standards easier to adopt for those who may come across my posts in the future.
My only beef really is that all pages I find where people apparently figure things out...they don't post any code! At least others can learn from what I'm posting...I'm not just trying to find an answer...I'm trying to make standards easier to adopt for those who may come across my posts in the future.
- JAB Creations
- DevNet Resident
- Posts: 2341
- Joined: Thu Jan 13, 2005 6:44 pm
- Location: Sarasota Florida
- Contact:
Re: Function to detect and add ID's from innerHTML and AJAX?
SOLVED!
Thanks to Xavier Amado's post here...
http://xavierdeveloper.blogspot.com/200 ... nce-1.html
...I realized how to call the function...which was odd but then again I've never encountered that sort of function before which completely threw me off.
Here are all the files and everything works in IE8RC1, Safari 4 Beta, Opera 10 Alpha, and Firefox 3. I haven't bothered with backwards compatibility yet so if anyone reads this as an archive feel free to contact me if you can't reply.
.htaccess
index.html
XMLHttpRequest_responseXML.js
XMLHttpRequest_responseXML.php
Thanks to Xavier Amado's post here...
http://xavierdeveloper.blogspot.com/200 ... nce-1.html
...I realized how to call the function...which was odd but then again I've never encountered that sort of function before which completely threw me off.
Here are all the files and everything works in IE8RC1, Safari 4 Beta, Opera 10 Alpha, and Firefox 3. I haven't bothered with backwards compatibility yet so if anyone reads this as an archive feel free to contact me if you can't reply.
.htaccess
Code: Select all
AddType application/javascript .jsCode: Select all
<?php header("content-type:application/xhtml+xml;"); echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><title>XMLHttpRequest: responseXML Example</title><style type="text/css">body, html {background-color: #456978; color:#dee; font-family: Verdana;}a:link, a:visited {color:#234; font-family: Verdana;}a:focus, a:hover, a:active {color:#fff;}div.test {background-color: #f00;}img.imgborder {border: #f0f solid 30px;}img.test {border: #0ff dotted 30px;}span.test {background-color: #ff0; color: #000;}</style><script language="javascript" type="text/javascript" src="XMLHttpRequest_responseXML.js"></script><script type="text/javascript">//<![CDATA[function change(id, newClass) {var identity=document.getElementById(id); identity.className=newClass;} function getElementByIdMXL(the_node,the_id){ //get all the tags in the doc var node_tags = the_node.getElementsByTagName('*'); for (i=0;i<node_tags.length;i++) { //is there an id attribute? if (node_tags[i].hasAttribute('id')) { //if there is, test its value if (node_tags[i].getAttribute('id') == the_id) { //and return it if it matches return node_tags[i]; } else { return '??'; } } } return false;} function getElementByIdXML(node,id){ //var nodes = node.getElementsByTagName('*'); //var nodes = xmlDoc.getElementsByTagName('*');var nodes = document.getElementById('ajax_here').getElementsByTagName('*'); for (var i=0;i<nodes.length;i++) { if (nodes[i].hasAttribute('id')) { if (nodes[i].getAttribute('id') == id) { return nodes[i]; //matching id } } } return false;}//]]></script></head> <body> <div style="background:#487987; border:1px solid #112233; margin: auto; padding:10px; width:770px;"> <div id="ajax_here"></div> <div><a href="javascript:alert(getElementByIdXML('xmlDoc','test_span').getAttribute('title'))">Alert AJAX span element title.</a></div><div><a href="javascript:alert(getElementByIdXML('xmlDoc','response').getAttribute('class'))">Alert AJAX span element class.</a></div><div><span onclick="getElementByIdXML('xmlDoc','response').className='test';return false;">Change class of 'test_span' to class 'test'.</span></div><div><span onclick="change('response','test');" style="color: #ff0; font-size: 22px;">Change class of 'test_span' to class 'test1'.</span></div><div><span onclick="change('response','test'); change('img_test','test');" style="color: #ff0; font-size: 22px;">Change class of 'test_span' to class 'test2'.</span></div> <h3>XMLHttpRequest: responseXML Example</h3> <div><span style=" font:13px/12pt verdana; letter-spacing:1px">Complete Example demonstrating the use of XML HttpRequest's "responseXML"</span></div><div><span style="color:#334455; font:8pt verdana; letter-spacing:1px" >( By Kostas Zotos 8/2008 ) </span></div> <form><textarea name="CellData" id="CellData" style="background:#659aa7; border:1px solid #234; height:110px; margin: 2px auto 2px auto; width: 100%;">This text will be replaced by the XML sent by PHP... (Click the button to send some data to PHP..)</textarea> <div><input type="button" style="background:#659aa7; border:1px solid #234; height:25px; margin: 2px auto 2px auto; width: 100%;" value="Click to send the current Date and Time" onclick="SendData(new Date())" /></div></form> </div> </body></html>Code: Select all
<?php header("content-type: application/javascript");?>
var xmlhttp;
function SendData(Arg)
{
xmlhttp=null;
var Url='XMLHttpRequest_responseXML.php';
if (window.XMLHttpRequest) {xmlhttp=new XMLHttpRequest();}
else if (window.ActiveXObject) {xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=onStateChange;
Url=Url+'?Date='+escape(Arg)+'&NoCache='+new Date().getTime();
xmlhttp.open('GET', Url, true);
// xmlhttp.overrideMimeType('text/xml');
xmlhttp.send(null);
}
else
{
alert('The XMLHttpRequest not supported');
}
}
function onStateChange()
{
if (xmlhttp.readyState==4)
{
if (xmlhttp.status==200)
{
var xmlDoc=xmlhttp.responseXML;
var DateNode=xmlDoc.getElementsByTagName('Date')[0].firstChild.nodeValue;
var Xml2String;
if (!xmlDoc.xml) {Xml2String= new XMLSerializer().serializeToString(xmlDoc);}
else {Xml2String=xmlDoc.xml}//IE
document.getElementById('CellData').value=Xml2String;
if (!document.ELEMENT_NODE)
{
document.ELEMENT_NODE = 1;
document.ATTRIBUTE_NODE = 2;
document.TEXT_NODE = 3;
document.CDATA_SECTION_NODE = 4;
document.ENTITY_REFERENCE_NODE = 5;
document.ENTITY_NODE = 6;
document.PROCESSING_INSTRUCTION_NODE = 7;
document.COMMENT_NODE = 8;
document.DOCUMENT_NODE = 9;
document.DOCUMENT_TYPE_NODE = 10;
document.DOCUMENT_FRAGMENT_NODE = 11;
document.NOTATION_NODE = 12;
}
document._importNode = function(node, allChildren)
{
switch (node.nodeType)
{
case document.ELEMENT_NODE:
var newNode = document.createElement(node.nodeName);
if (node.attributes && node.attributes.length > 0) {for (var i = 0, il = node.attributes.length; i < il;) {newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i++].nodeName));}}
if (allChildren && node.childNodes && node.childNodes.length > 0) {for (var i = 0, il = node.childNodes.length; i < il;) {newNode.appendChild(document._importNode(node.childNodes[i++], allChildren));}}
return newNode;
break;
case document.TEXT_NODE:
case document.CDATA_SECTION_NODE:
case document.COMMENT_NODE:
return document.createTextNode(node.nodeValue);
break;
}
}
if (document.importNode) {alert('standard'); document.getElementById('ajax_here').appendChild(document.importNode(xmlDoc.getElementsByTagName('div')[0],true));}
else {alert('ie'); document.getElementById('ajax_here').appendChild(document._importNode(xmlDoc.getElementsByTagName('div')[0],true));}
}
else
{
document.getElementById('ajax_here').appendChild(Xml2String);
}
}
}Code: Select all
<?php
header('Content-Type: text/xml');
header ('Cache-Control: no-cache');
header ('Cache-Control: no-store' , false); // false => this header not override the previous similar header
if (isset($_GET['Date']))
{
$Date=trim($_GET['Date']);
$Date=strip_tags($Date);
}
else
{
$Date=@date("l, d F Y ( H:i:s A )");
}
/*<?xml version="1.0" encoding="UTF-8"?>*/
$xmlStr='<div xmlns="http://www.w3.org/1999/xhtml" class="test579" id="response">1234
<div>aa<span class="test" id="test_span" title="TITLE TEXT HERE!">bb</span></div>
<div><img alt="test image" class="imgborder" id="img_test" src="malia-fallen_angel.jpg" title="test image" /></div>
<data id="ajax_id1"><Date id="ajax_id2">'.$Date.'</Date><ip>'.$_SERVER['REMOTE_ADDR'].'</ip></data>
</div>
';
echo $xmlStr;
?>