views:

56

answers:

2

I'm trying to load specific content from a XML to a HTML div. I'm using a function with parameters to do this.

This my call to function:

loadDoc("news.xml","destak-article","article");

this should send a request for the xml file, get the content of «article» tag and put it on the «destak-article» div.

Here's my function body:

function loadDoc(url,id,tagname){

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

    xmlhttp.open("GET",url,false);
    xmlhttp.send();
    xmlDoc = xmlhttp.responseXML;

    document.getElementById(id).innerHTML = xmlDoc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}

But this doesn't seem to work. On Chrome js console I get this error:

Cannot call method 'getElementsByTagName' of null
On Firebug I get:
xmlDoc.getElementsByTagName(tagname)[0] is undefined

Any help is much appreciated.

A: 

You need to register a handler function that will be called once the request is complete. You can see an example of how to do that here.

What's happening in your case is that you're trying to get the xmlDoc immediately after sending the request and the server hasn't had time to process the request and respond yet.

Pat
He is doing a synchronous call - that is the third argument to xmlhttp.open set to false.
jira
@jira whoops - thanks for the correction.
Pat
A: 

Did you verify the server response? Use some error checking in your code. For example:

if (xmlhttp.status == 200) { 
document.getElementById(id).innerHTML = xmlDoc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}
else {
 alert('error');
}
jira