1

Im currently in the learning process with AJAX & JavaScript..

I have a quick question to the wise..

How can i turn the code below into a timed event instead of an OnClick event.

**For Example i would like to refresh the "showlist" DIV every 5 seconds...

I understand that this is working code and goes against the rules of the site but if i were to post my non working code it would just confuse things as it has me..

I am trying to slowly understand the basics :)

Any guidance would be greatly appreciated

<!DOCTYPE html>
<html>
<head>
<script>

function loadXMLDoc()
{

var xmlhttp;
if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

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

}
}

xmlhttp.open("GET","playlist.php?t=" + Math.random(),true);
xmlhttp.send();

}
</script>
</head>

<body>
<h2>Ajax Testing...</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="showlist"></div>
</body>

</html>
Justin
  • 135
  • 2
  • 12
  • So you don't want onclick anymore? What should start loading? On page load? – dfsq Feb 03 '14 at 19:07
  • @dfsq i would like to remove the "OnClick" and have the playlist.php retrieved and shown on screen every 5 seconds. – Justin Feb 03 '14 at 19:09
  • I would advice to take a look to `jQuery` instead of XMLHttpRequest which is much more complicated to start (I guess), `$.ajax`. About what you want to do, you can use the setTimeout js function to automatically call the loadXMLDoc function each 5s. The loadXMLDoc would have to deal with the ajax request. – Vadorequest Feb 03 '14 at 19:09
  • @vadorequest i would like to only use Javascript & AJAX for this. I am in the learning process and want to understand the basics before i move to more equip and quicker methods such as JQuery, thank you.. – Justin Feb 03 '14 at 19:11
  • @Justin As you want, but use jQuery would make your learning easier I guess. I never used XMLHttpRequest and I don't think it's really better or that I would have better understood Ajax with it. Probably not btw... :) – Vadorequest Feb 03 '14 at 19:26
  • 1
    thanks @Vadorequest I understand that i need to test different methods. I will look into JQuery soon.. – Justin Feb 03 '14 at 19:32
  • Everybody learn in a different way, good luck ;) – Vadorequest Feb 03 '14 at 19:37

3 Answers3

1

You can change loadXMLDoc function to make use of setTimeout. Consider this example:

function loadXMLDoc() {

    var xmlhttp,
        timer;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("showlist").innerHTML = xmlhttp.responseText;
        }
    };

    xmlhttp.onerror = function() {
        clearTimeout(timer);
    };

    xmlhttp.open("GET", "playlist.php?t=" + Math.random(), true);
    xmlhttp.send();


    timer = setTimeout(loadXMLDoc, 5000);
}

Function issues AJAX request and set up a 5s timeout. I also added basic onerror callback to clear timer just in case.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • @dfsk Thank you.. i have implemented your code but nothing displays on screen... Do i need to somehow start the cycle off so that the data display on screen.. Im guessing that i need to add the "loadXMLDoc()" somehow as before thats how the Onclick event called the script – Justin Feb 03 '14 at 19:21
  • You should initiate process in proper moment. For example on page load. Or just call this function `loadXMLDoc()`. – dfsq Feb 03 '14 at 19:25
  • @dsfq Thank you for your help... It is really important for me to see basic methods... You have done this... Very Kind! – Justin Feb 03 '14 at 19:35
0

I once made a kind of tv, which automatically changed the 'screen' after 3 seconds.

Maybe you can re-use my code?

// This is the div called myScreen
var myScreen = document.getElementById('myScreen');
// This is an array, which is holding the names of the pictures
var myPics = ['img-screen1.png','img-screen2.png'];
// This is looking at how many things the array holds
var totalPics = myPics.length;
// Now this is where the magic begins, this keeps looping around and around, and 
// makes sure all the pictures are being showed, one by one.
var i = 0
function loop() {
    if(i > (totalPics - 1)){
        i = 0;
    }
    myScreen.innerHTML = '<img src="images/'+myPics[i]+'">';
    i++;
    loopTimer = setTimeout('loop()',3000);
}
loop();

I hope you can re-use this for your project, and I hope you kind of understand what I mean, if I need to clarify, just ask me :).

So what you need to do, is refresh the array when you got new item in your showlist.

JiFus
  • 959
  • 7
  • 19
0

This function (if placed inside the same script tag after your loadXMLDoc fn) will execute and call your function and then itself again every 5 seconds (recursively). You could call setInterval instead, but that runs the risk of occasionally missing a cycle if the js engine is busy:

(function doMeSelf(){
    setTimeout(function(){
        loadXMLDoc();
        doMeSelf();
    },5000);
})();

Enclosing the function def inside parens, and then followed by () is called an immediately invoked function expression.

See this question for some background: What do parentheses surrounding a object/function/class declaration mean?

Community
  • 1
  • 1
Faust
  • 15,130
  • 9
  • 54
  • 111