How to Automatically Refresh Data on Page Using Ajax on an Interval?

Posted by Karnak on Stack Overflow See other posts from Stack Overflow or by Karnak
Published on 2012-06-02T10:02:15Z Indexed on 2012/06/02 10:40 UTC
Read the original article Hit count: 170

Filed under:
|

I would like to load an XML file every 30 seconds and display its contents inside an HTML page.

So far I know how to load the file, but I don't know how to automatically refresh it and display its updated contents. It would also be great if it did some error checking and if it displayed error.png image when it's not able to load data.xml file.

Here is my code:

<head>
  <script>
    window.XMLHttpRequest
        {
        xmlhttp = new XMLHttpRequest();
        }
    xmlhttp.open("GET", "data.xml", false);
    xmlhttp.send();

    loadXMLDoc = xmlhttp.responseXML;
    f = loadXMLDoc.getElementsByTagName("foo")

    function buildBar(i)
        {
        qux = (f[i].getElementsByTagName("qux")[0].childNodes[0].nodeValue);
        document.getElementById("displayBar").innerHTML = qux;
        }
  </script>
</head>
<body>
  <script>
    document.write("<ul>");
    for (var i = 0; i < f.length; i++)
        {
        document.write("<li onclick='buildBar(" + i + ")'>");
        document.write(f[i].getElementsByTagName("bar")[0].childNodes[0].nodeValue);
        document.write("</li>");
        }
    document.write("</ul>");
  </script>

  <div id="displayBar">
  </div>
</body>

After searching the internet for a few hours I found many examples on how to do this, but I didn't know how to implement it in my particular case. I am not a programmer, so please be kind.

I would really appriciate any help. It would mean a lot.

© Stack Overflow or respective owner

Related posts about AJAX

Related posts about xmlhttprequest