I’m developing an AJAX-based risk-style game, and a collaborator (who has since left) wrote this code:
function init() {
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","risk.xml",true);
xmlhttp.send(null);
xmldoc=xmlhttp.responseXML;
[snip]
document.getElementById('player').value='red'
[snip]
redterrs=xmldoc.getElementsByTagName('redterrs')[0]
blueterrs=xmldoc.getElementsByTagName('blueterrs')[0]
purpleterrs=xmldoc.getElementsByTagName('purpleterrs')[0]
greenterrs=xmldoc.getElementsByTagName('greenterrs')[0]
When I try to execute this I get this error in WebKit: “Uncaught TypeError: Cannot call method ‘getElementsByTagName’ of null” on “redterrs=xmldoc.getElementsByTagName(‘redterrs’)[0]”, but when I do it in Firefox with Firebug it tells me xmldoc is not defined.
Edit: In case anyone wanted to see more of this, project is hosted at http://code.google.com/p/risk-board-game.
You are getting the XML document asynchronously, but you are not using an event handler to find out when the XML document has been received. Since you probably should be doing this synchronously, and since it is much simpler, try this in place of line 3: