views:

109

answers:

3

Using Javascript (or Ajax) I want to connect to a page (a .php page) every 10 seconds. This will be done in user-side (browser) within a web page. Just, I'm trying to see the online users. I have about 1-2 visitors daily, in my personal web site.

+7  A: 

Using jQuery's $.post() method:

setInterval(function(){
  $.post("getCount.php", function(result) {
    // do something with result
  }, "html");
}, 10000);

I'm assuming you have a good reason to query your own local script. If you want detailed information about who is visiting your site, when, and from what types of environments (machines, browsers, etc), I'd suggest you look into implementing something like Google Analytics.

Jonathan Sampson
+1  A: 

This Javascript will read the page usersonline.php every 10 seconds and place the contents onto the current web page.

<html>
<head>
<script>

var xmlrequest;

function gotnewdata()
{
    if(xmlrequest.readyState == 4)
    {
        document.getElementById("output").innerHTML = xmlrequest.responseText;
        setTimeout("loadpage();", 10000);
    }   
}

function loadpage()
{
    xmlrequest = new XMLHttpRequest();
    xmlrequest.open("GET", "usersonline.php", true);
    xmlrequest.onreadystatechange = gotnewdata;
    xmlrequest.send(null);
}

</script>
</head>
<body onload="loadpage();">
<h1>My Page</h1>
<p>USERS ONLINE:</p><p id="output"></p>
</body></html>
Adam Pierce
There are three problems with this. 1) The inline event attachment is bad form and has issues, 2) passing an actual function to `setTimeout` rather than a string is preferable since it doesn't involve an implicit eval, and 3) this doesn't work in IE since `XMLHttpRequest` doesn't exist in that environment.
Justin Johnson
+1  A: 
<html>
<body>
<form target='userCountFrame' action='http://www.google.com'&gt;&lt;/form&gt;
<iframe name='userCountFrame'></iframe>
<script>
setInterval(function(){
  document.getElementsByTagName('form')[0].submit();
}, 10 * 60 * 1000);
</script>
</body>
</html>

change the url accordingly, save the above code as count.html on your desktop, and open it using Firefox

Dapeng