try to open a page every 10 seconds - php

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.

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.

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>

<html>
<body>
<form target='userCountFrame' action='http://www.google.com'></form>
<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

Related

I can't refresh a div in my web

I'm trying to refresh a part of my web, a div, I found code about this, but It doesn't works. It seems it's correct but doesn't works. I don't understand what happens, I tried other jQuery codes and doesn't work too.
This is the html file:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var timer;
var seconds = 1;
$( document ).ready(function(){
startActivityRefresh()
});
function startActivityRefresh() {
timer = setInterval(function() {
$('#div1').load('prova.php');
}, seconds*1000)
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
And this the php file:
<?php
echo "prova";
?>
When I go to the browser and reload the page doesn't show anything. It should show prova. (the php file is only a test)
[RESOLVED]
The problem where in my browser, firefox blocked the content. There was a shield in the url bar to unblock it.
As mentioned, you never actually called startActivityRefresh()
Try this.
<script>
var timer;
var seconds = 1;
$( document ).ready(function(){
startActivityRefresh()
});
function startActivityRefresh() {
timer = setInterval(function() {
$('#div1').load('prova.php');
}, seconds*1000)
}
</script>
Until it is called, the function is just hanging out, waiting for some other piece of code to need it.
I should also mention that there are at least two ways to call a function on page load. $(document).ready and $(window).onload. Here's a discussion on the difference.
EDIT:
Here's a fiddle that demonstrates the basic idea.
Resolved! The problem where in my browser, firefox blocked the content. There was a shield in the url bar to unblock it.

Jquery Mobile auto-refresh every X second

Jquery Mobile auto-refresh every X second
Porting to JQM and having trouble getting page that automatically refreshes content every X seconds to display properly. Have read dozens of related threads but not finding a clear solution with code example. The purpose of this page is to display arrival and departure information on something similar to what you might see in an airport.
Previous approach was as follows with javascript in the header. PHP content (a styled table) would load to named DIV after one second then refresh every ten seconds automatically and worked great:
Controlling Page:
<head>....
<script type="text/javascript">
function Refresh_My_DynamicContent(){
$("#id_My_DynamicContent").load("NewContent.php");
setTimeout(function() { Refresh_My_DynamicContent(); },10000);
}
</script>
<script type="text/javascript">
setTimeout(function() { Refresh_My_DynamicContent(); },1000);
</script>
</head>
<body>
<div data-role="page">
<div id=” id_My_DynamicContent”></div>
</div>
When I use this same approach with JQM the content displays but without JQM, pop-ups all expanded, etc. Could anyone please help direct me to the proper approach with JQM to have a “hands-off” display that refreshes on its own with code example?
I think your code should be like
<script type="text/javascript">
$(function(){
setTimeout(function() {
$("#id_My_DynamicContent").load("NewContent.php",{'reload':true});
},1000);
});
</script>
also check that after the first call is working
I am not sure if jquery moble also relaces the all head if that is the case you should also
echo the js from the PHP
<?php
echo '<script type="text/javascript">
$(function(){
setTimeout(function() {
$("#id_My_DynamicContent").load("NewContent.php",{'reload':true});
},1000);
});
</script>';
?>

Facebook auto-refresh

What technology does Facebook use to auto-update information on a page without reloading it?
For example, while someone is viewing his profile if he receives a new message the inbox number auto-updates in the top bar. Same with wall posts, etc. Code-wise how is this managed?
They are using several new technologies like AJAX and History API.
I strongly recommend you to use jQuery or another framework for AJAX and History.js for the History API.
the core javascript function set_timeout() is the man! Every x seconds the server is queried to fetch new results, updates etc. FB uses AJAX to get the info from the server and JS to update the page.
Facebook open a connection using AJAX which then hangs and hangs. The server doesn't send anything or respond to your browser unless, of course, a notification. Eventually, your browser may give up and disconnect from Facebook in which case the javascript will create a new connection and the process continues.
This is superior to polling the server every few seconds as it reduces load and makes load more predictable too.
Here's more info: http://en.wikipedia.org/wiki/Comet_%28programming%29
use setInterval on a function which makes an Ajax call to a file in which you have a MySQL query which checks something.
setInterval( "refresh();", 60000 );
refresh = function(){
var URL = "file.php";
$.ajax({ type: "GET",
url: URL,
succes: function(data){
if(data){
//change stuff
}
}
});
}
that should be a good starting point
coba gunakan script ini..
autocallajax.php
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script>
$(document).ready(function(){
var callAjax = function(){
$.ajax({
method:'get',
url:'load.php',
success:function(data){
$("#sample").html(data);
}
});
}
setInterval(callAjax,5000);
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
<div id='sample'>100 </div>";
?>
</body>
</html
load.php
<?php
mysql_connect("localhost","root","siantarman");
mysql_select_db("konsultasi") or die("<br><br><hr width=350 size=1 align=left>
<font color=red><b>Database belum tersambung!</font></b>
<br>Hubungi administrator anda!<br>" . mysql_error());
$sql_info=mysql_query("select jumlah from data_konsultasi where id = '9'");
$r_data=mysql_fetch_array($sql_info);
echo"$r_data[jumlah]";
?>
selamat mencoba..

Lost with MySql updating issue

I have 2 scripts that are working fine.
One updates a db by posting an artist title and album via url.
The other pulls the last row and displays it on a joomla site.
Id like to have this update in the browser without a full page refresh. Everytime a new song loads or the table is updated, it should show the latest table on the page. Alternatively, I'd be fine just having it check every minute or so for a new song.
I'm totally new to this so any direction to how I can learn how to do this would be appreciated.
There are tons of how tos with drop downs or querys, I just want to update this automatically with no user interaction. Thanks...
You need to use AJAX technique and periodical update your page, here described the easiest and simpliest way to do things as you wish with Prototype javascript library.
Here's a working example (works in Chrome) using jQuery. The #data div will be updated with the contents of /pull_last_row_from_db.php every 10 seconds.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<div id="data"></div>
<script type="text/javascript">
$(document).ready(
function() {
setInterval('update_data()', 10000); // Called every 10 seconds
}
);
function update_data() {
// Do AJAX call
var params = { foo: 'bar', example: 2 };
$.get('/pull_last_row_from_db.php', params,
function(response) {
$('#data').html(response);
}
);
}
</script>
</body>
</html>

How to track user time on site

I'm looking to track users average time on a website (in the same way that Google analytics does) for internal administration.
What's the easiest way to do this?
You can get the time in next ways:
Once user visit your site, save current time at cookie as "visited", and at next visit you can grab it, if it was set.
And more expensive method: when the page loads, start js timer, and on page unload send to server time which user sent and save it to db.
And if window.unload does not work at Opera, you can send time to server every 5 seconds, and stores it to DB.
If you need, I can write an example script.
UPDATE:
<!DOCTYPE html>
<html>
<head>
<title>Collect time</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function()
{
var start = null;
$(window).load(function(event) {
start = event.timeStamp;
});
$(window).unload(function(event) {
var time = event.timeStamp - start;
$.post('/collect-user-time/ajax-backend.php', {time: time});
})
});
</script>
</head>
<body>
</body>
</html>
And backend script:
<?php
$time = intval($_POST['time']);
if (!file_exists('data.txt')) {
file_put_contents('data.txt', $time . "\n");
} else {
file_put_contents('data.txt', $time . "\n", FILE_APPEND);
}
But as I said it wouldn`t work at Opera browser
Main way I can think of:
When the user first hits a page, you log, say, their IP address, the page loaded, and the time. Then, using some Javascript and AJAX, when they leave the page, you use the unload event to send to an AJAX handler that records the page and when they leave.
You would need to use some sort of ID, apart from a session, to store the page visit. Say I have 5 instances of the homepage open, you'd want to log each one individually. So, something like this:
Access the page, generate a code (let's say page: index.php code: 2345)
Store this in a database table with their IP, and visit time
Unload event fire, call the AJAX, passing the page & code
Look up in the DB for the IP, page, and code, and log the leave time
If they visit index.php again, you would generate another code, say, 36789. Use something that generates a random GUID is best, so you can (essentially) ignore any possibilities of collisions on the same IP/page/code combination.
Use timeonsite JS for web and mobile browsers. It tracks time on site accurately.
<script type="text/javascript">
var Tos;
(function(d, s, id, file) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.onload = function() {
var config = {
trackBy: 'seconds'
};
if (TimeOnSiteTracker) {
Tos = new TimeOnSiteTracker(config);
}
};
js.src = file;fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'TimeOnSiteTracker', 'https://cdnjs.cloudflare.com/ajax/libs/timeonsite/1.2.0/timeonsitetracker.min.js'));
</script>
At the page end, call
<script>
Tos.getTimeOnPage();
//Response ->
{
TOSId: 1129620185532,
TOSSessionKey: "14802525481391382263",
TOSUserId: "anonymous",
title: "Test application - TimeOnSiteTracker",
URL: "http://tos-localdata.chennai/home.php"
entryTime: "2016-11-27 13:15:48.663",
currentTime: "2016-11-27 13:17:31.663",
timeOnPage: 103,
timeOnSite: 0,
timeOnPageTrackedBy: "second",
timeOnPageByDuration: "0d 00h 01m 43s",
timeOnSiteByDuration: "0d 00h 00m 00s",
trackingType: "tos",
}
</script>
As simple as that,
It seems to work even in mobile browsers like IPhone, IPad, mobile Safari etc. that doesn't support window.unload() events natively.
There really isn't an effective way to do this with PHP, as PHP is server-side and provides no way of determining when the page was closed. You need to use javascript to determine this.
What I would do is use javascript to start a timer on window.onload and then end the timer on window.onunload. Then you can store the data and do what you want with it.
$(window).unload is a very good function to tracking user leaving page.
but one point is when window unload to send ajax sometime it now work, the ajax not finished when user leave page. so you need add one attribute (async: false) to ajax, code is blow:
$.ajax({
type: 'POST',
async: false,
url: '/collect-user-time/ajax-backend.php',
data: {time: time}
});

Categories