Charles Kiel Charles Kiel - 5 months ago 45
Javascript Question

Cannot read property 'getElementsByTagName' of null

I've been searching around for answers to this particular problem for about two days now. I can't seem to figure out what's going on with it. All this seemed to have worked in the past but isn't working anymore.

XML:

<ZipCodes>
<results>
<city>Chicago</city>
<state>IL</state>
<timezone>-6</timezone>
</results>




javascript:

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("GET","_checkzip.php?zip="+str,true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

x=xmlDoc.getElementsByTagName("results");
i=0;



document.forms["signup"]["City"].value=(x[i].getElementsByTagName("city")[0].childNodes[0].nodeValue);
document.forms["signup"]["states"].value=(x[i].getElementsByTagName("state")[0].childNodes[0].nodeValue);
document.forms["signup"]["TimeZone"].value=(x[i].getElementsByTagName("timezone")[0].childNodes[0].nodeValue);


and the error I get is

Cannot read property 'getElementsByTagName' of null


when I try x=xmlDoc.getElementsByTagName("results"); The xml is deffinetly coming in on the network response when I look at the debug in Chrome.

Answer

You can use an event handler on an XMLHttpRequest's onreadystatechange to make sure the request is done. If the status of readyState is 4, the operation is complete.

Currently you're asking for data that hasn't been transmitted yet.