views:

87

answers:

3

Hi, this is my code:

 <script language="javascript">
    function refresh() {
        try {
            xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {}
        xmlhttp.onreadystatechange = triggered;
        xmlhttp.open("GET", "data.php");
        xmlhttp.send(null);
    }

    function triggered() {
        if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
            document.getElementById("ins").innerHTML = xmlhttp.responseText;
        }
        document.getElementById("loading").style.display = "block";
    }
</script>

<a href="javascript:refresh();">Refresh List</a>

The functions fails on the second time i call it,

Error: document.getElementById("loading") is null

Very strange, any fix for it?

+4  A: 

Is it possible that loading is a child of ins and is overwritten by triggered()?

Open Source
yes, but that the only way it worked for me.<div id="ins"><div id="loading"></div</div>
JQman
You are overwriting `ins`, thus destroying `loading`. You need to place `loading` elsewhere.
Open Source
+1  A: 

I'm not an expert on javascript, but I guess:

The call to document.getElementById("loading") is not limited to xmlhttp.readyState==4.

It is called for all readyStates from 0 to 4. If the line

document.getElementById("ins").innerHTML = xmlhttp.responseText;

makes significant changes to the page (probably "remove" the element "loading"), the following

document.getElementById("loading").style.display = "block";

leads to an error.

Sebastian Seifert
+1  A: 

Move the loading div from outside of the ins div:

<div id="loading"></div>  
<div id="ins"></div>  

and change the javascript to the following:

function triggered() {  
    if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {  
        document.getElementById("ins").innerHTML = xmlhttp.responseText;  
    }  
    document.getElementById("loading").style.display =  
                (xmlhttp.readyState == 4) ? "none" : "block";
}  

This will hide the loading div for you when you finish and will re-show it next time you invoke this method.

mynameiscoffey
thx, that worked!
JQman