October 9, 2008

wrong way to load XML in JavaScript

There are many examples of how to load an XML file in JavaScript, they include the load function of type document:


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);
}
}
xmlDoc.async=false;
xmlDoc.load("localfile.xml");

safari will error out on the last line of this code. xmlDoc.load is not part of the w3c standard. Instead use xmlDoc.open.

 req = false;
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
req = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if(req) {
req.onreadystatechange = processReqChange;
req.open("GET", "localfile.xml", true);
req.send("");
}


function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
parseXML();
} else {
alert("There was a problem retrieving the XML data:\n" +
req.status);
}
}
}

This method is called from loadXMLDoc and is passed the string to the URL. Then the code it will execute when the file is opened will be at parseXML(). Also, make note that in this second example, if you want to run getElementsByTagTame, you will want to rn them on req.responseXML instead of xmlDoc.

October 8, 2008

AJAX on free hosting

a lot of ISP's offer free hosting, you expect a little less for a free account, however I did not expect that the MIME type for .xml files would be text/plain. I was blown away! That was enough for req.status != 200. While some browsers support an override of MIME type, IE does not. So bottom line, no AJAX support. However if you are using a free host, you are not going to have server-side scripts touching the XML either. So hard coding the data into the document worked just fine for me.