Change Language


Follow Navioo On Twitter

Alternate Ajax Techniques Part 2- Import the XML document

At the moment it only works in Explorer 5+ on Windows and Mozilla/Firefox !!!!!!!.
Mozilla imports an XML document through the method document.implementation.createDocument(). First check if document.implementation is supported, then check if document.implementation. createDocument() is supported. .

Internet Explorer

Internet Explorer on Windows doesn't support document.implementation . Instead, you must create an ActiveX Object that will contain the XML document. So we see if the browser can create ActiveXObjects:

The script

function importXMLDoc(myXml) 
{
try //Internet Explorer
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  }
  catch(e)
  {
  try //Firefox, Mozilla, Opera, etc.
    {
    xmlDoc=document.implementation.createDocument("","",null);
    }
    catch(e) {
      alert(e.message);
    }
  }
try 
  {
  xmlDoc.async=false;
  xmlDoc.load(myXml);
  return(xmlDoc);
  }
  catch(e) {
    alert(e.message);
  }
return(null);
}

1.1 Simple Example ( Example 1) (Firefox 3 compatible)


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" >
function import_xmlDoc(myXml)
{
var myxmlDoc=null
try //Internet Explorer
{
myxmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
myxmlDoc=document.implementation.createDocument("","",null);
}
catch(e) {
alert(e.message);
}
}
try
{
myxmlDoc.async=false;
myxmlDoc.load(myXml);
return(myxmlDoc);
}
catch(e) {
alert(e.message);
}
return(null);
}

</script>
</head>

<body>

<script type="text/javascript">
StartLoadingXml=function()
{
var obj_ResponseFromXml=document.getElementById("ResponseFromXml");
var myxmlDocument=import_xmlDoc("my.xml.php");
if(myxmlDocLoaded)
{
if(window.ActiveX)
{
var el=myxmlDocument.getElementsByTagName("root");
}else{
//PATCH FOR Firefox3 !!!!!!!!!!
var node=myxmlDocument.firstChild;
document.getElementById("storageXml").appendChild(document.importNode(node,true));
var el=document.body.getElementsByTagName("root");
}


alert("myxmlDocument is loaded, ready for use ");
var txt=el[0].firstChild.nodeValue;
obj_ResponseFromXml.innerHTML=txt;
myxmlDocument=null;
}
}

</script>
<input type="button" onclick="StartLoadingXml()" name="start" value="StartLoadingXml"/>
<div id="ResponseFromXml" style="display:none"></div>
<div id="storageXml" style="display:none"></div>
</body>
</html>

The XML file called my.xml.php contains a 2 line:

Assure you have correct header type in your xml file if is dynamic generated. Firefox return error in xml interpretation /parsing

<?header('Content-type: application/xml; charset="utf-8"',true);?>
<myxml><root>Hello world!</root></myxml>

 


DEMO of Example 1


Other Techniques
- Using <iframe/> element
- Dynamic Script Loading
- Images and Cookies

Ajax Javascript feed

↑ Grab this Headline Animator