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}
});
Related
I have a website where I need to update a status.
Like for a flight, you are departing, cruise or landed.
I want to be able to refresh the status without having my viewers to have and reload the whole page. I know there is a way to do it with AJAX and jQuery, but I don't have any understanding of how that works. I also don't want them to have and click a button.
If anybody knows how that would be done I much appreciate it!
This is typically achieved with a technique called AJAX. This technique loads data asynchronously (in the background) so it can update your content without needing to reload the page.
The easiest way to implement AJAX is with the jQuery load() method. This method provides a simple way to load data asynchronous from a web server and place the returned HTML into the selected element. The basic syntax of this method is: $(selector).load(url, data, complete); where the arguments are:
selector the existing HTML element you want to load the data into
url a string containing the URL to which the request is sent
data (optional) a plain object or string that is sent to the server with the request
complete (optional) a callback function that is executed when the request completes
The required URL parameter specifies the URL of the file you want to load.
The optional data parameter allows you to specify data (i.e. key/value pairs) that is sent to the web server along with the request. The optional complete parameter can be used to reference a callback function. The callback is fired once for each selected element.
A visualisation:
A simple example of using load(), where we load data dynamically when a button is pressed:
DEMO
// no need to specify document ready
$(function(){
// optional: don't cache ajax to force the content to be fresh
$.ajaxSetup ({
cache: false
});
// specify loading spinner
var spinner = "<img src='http://i.imgur.com/pKopwXp.gif' alt='loading...' />";
// specify the server/url you want to load data from
var url = "http://fiddle.jshell.net/dvb0wpLs/show/";
// on click, load the data dynamically into the #result div
$("#loadbasic").click(function(){
$("#result").html(spinner).load(url);
});
});
If you don't want to use the jQuery library, you can also use plain Javascript. Loading content is slightly more difficult that way. Here is an example of how to do it with javascript only.
To learn more about AJAX, you can take a look at https://www.w3schools.com/xml/ajax_intro.asp
Suppose you want to display some live feed content (say livefeed.txt) on you web page without any page refresh then the following simplified example is for you.
In the below html file, the live data gets updated on the div element of id "liveData"
index.html
<!DOCTYPE html>
<html>
<head>
<title>Live Update</title>
<meta charset="UTF-8">
<script type="text/javascript" src="autoUpdate.js"></script>
</head>
<div id="liveData">
<p>Loading Data...</p>
</div>
</body>
</html>
Below autoUpdate.js reads the live data using XMLHttpRequest object and updates the html div element on every 1 second. I have given comments on most part of the code for better understanding.
autoUpdate.js
window.addEventListener('load', function()
{
var xhr = null;
getXmlHttpRequestObject = function()
{
if(!xhr)
{
// Create a new XMLHttpRequest object
xhr = new XMLHttpRequest();
}
return xhr;
};
updateLiveData = function()
{
var now = new Date();
// Date string is appended as a query with live data
// for not to use the cached version
var url = 'livefeed.txt?' + now.getTime();
xhr = getXmlHttpRequestObject();
xhr.onreadystatechange = evenHandler;
// asynchronous requests
xhr.open("GET", url, true);
// Send the request over the network
xhr.send(null);
};
updateLiveData();
function evenHandler()
{
// Check response is ready or not
if(xhr.readyState == 4 && xhr.status == 200)
{
dataDiv = document.getElementById('liveData');
// Set current data text
dataDiv.innerHTML = xhr.responseText;
// Update the live data every 1 sec
setTimeout(updateLiveData(), 1000);
}
}
});
For testing purpose: Just write some thing in the livefeed.txt - You will get updated the same in index.html without any refresh.
livefeed.txt
Hello
World
blah..
blah..
Note: You need to run the above code on the web server (ex: http://localhost:1234/index.html) not as a client html file (ex: file:///C:/index.html).
You can read about jQuery Ajax from official jQuery Site:
https://api.jquery.com/jQuery.ajax/
If you don't want to use any click event then you can set timer for periodically update.
Below code may be help you just example.
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
Above function will call after every 10 seconds and get content from response.php and update in #some_div.
If you want to know how ajax works, it is not a good way to use jQuery directly. I support to learn the native way to send a ajax request to the server, see something about XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://some.com");
xhr.onreadystatechange = function () {}; // do something here...
xhr.send();
I'm looking to set up an experiment to test 2 separate webpage layouts and find out which one allows users to scan the page and find information the quickest.
So in each layout there will be a link 'click me' with a unique ID. I will ask a group of users to view both layouts and click the link as soon as they see it.
I want to record how long it takes each user to click the link and record that time somewhere. So I'm thinking the solution might be a combination of jQuery/Ajax and PHP.
Anyone have any suggestions of stuff that's out there already or how this could be done, relatively easily? I'm a frontend designer rather than developer but have some jQuery knowledge.
Thanks in advance.
Steve
P.s - happy to use Wordpress or something off the shelf for this experiment.
Should be fairly simple, get the time in milliseconds when the page load, then again when the user clicks, and compare
var start = new Date();
$(function() {
$('button').on('click', function() {
var stop = new Date();
var elapsed = stop.getTime() - start.getTime();
});
});
FIDDLE
To store the times somewhere that you can access them and do stuff, you'll have to send the times to the serverside first.
$(function() {
$('button').on('click', function() {
var stop = new Date();
var elapsed = stop.getTime() - start.getTime();
$.ajax({
url : 'script.php',
data : {time : elapsed}
});
});
});
and on the server you'll get the times with
$_GET['time'];
then you'll have to figure out how and where to store them, I'd recommend setting up a database.
I've got a div that randomly shows 1 of 10 files on each pageload. I'd like this to reload on a set time interval of 8 seconds, giving me a different one of the 10 files each reload.
I've read a few of the related questions using jQuery .load as a solution but this doesn't quite work with my code since I'm not loading a specific file each time.
This is my div content:
<div id="tall-content">
<?
$random = rand(1,10);
include 'tall-files/' . $random . '.php';
?>
</div>
Thanks
Using only PHP to accomplish this is impractical. This example uses jQuery and PHP.
$(document).ready(function() {
$("#div").load("random.php");
var refreshId = setInterval(function() {
$("#div").load('random.php');
}, 8000);
$.ajaxSetup({ cache: false });
});
random.php
$pages = array("page1.php", "page2.php", "page3.php", "page4.php", "page5.php");
$randompage = $pages[mt_rand(0, count($pages) -1)];
include ($randompage);
while using PHP to generate the random content, you cannot get the div to reload that content without refreshing the entire page.
A better solution is to use AJAX. You can store that PHP code that's inside the div container as a seperate file, and use ajax to request that php file. You can also set an infinite loop to request the php file every 8 seconds. Here is a sample, but you will need to re-code it to your specification:
<script language="javascript" type="text/javascript">
<!--
function ajaxFunction(){
var ajaxRequest;
try{ajaxRequest = new XMLHttpRequest();} catch (e){try{ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try{ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");} catch (e){alert("Error: Browser/Settings conflict");return false;}}}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById('tall-content').innerHTML = ajaxRequest.responseText;
}
}
var url = "random.php";
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
//-->
</script>
The only missing part is the refresh timer, since I do not program a lot in javascript I can't help you there. But the goal in this case is to create a file "random.php", put the random generator there, and use this script above to make an ajax request to random.php, which will place the output of that php script in the div container with the id of "tall-content". So really, you need to create another javascript which loops indefinitely calling the function "ajaxFunction()" and wait 8000 milliseconds .
If you want to do this while the user is sitting back in the chair on your page, the answer is javascript.
You could use this function for example.
function recrusive_timeout_function() {
setTimeout(function() {
recrusive_timeout_function();
}, 8000);
}
If you want to include a php file in that div (which outputs some html). Ajax is your friend and JQuery as a user friendly and easy to use javascript framework which handles your thinks really nice.
I'm creating a system using jquery and php that pops up a small div when they get a private message on my website. The alert itself I have figured out, but I'm not sure how to gracefully cancel it.
I've made it so that clicking a link "[x]" hides the div, but how can I make the link send enough information to a php script to mark this alert as "read" in the database?
All the php script would need is the id of the alert in the database, but I've got no idea how to make it do that. There is also more than one notice displayed at a time, so I would need a way to have each link send the information necessary to the php script.
Here's the jquery that loads the div and the php that powers it.
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#mc').load('/lib/message_center.php').show("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
<script type="text/javascript">
$(document).ready(function(){
$('.delete').live('click', function(){
$('#mc').hide('slow');
});
});
</script>
The easiest solution would be to set the message you are displaying to read at the moment you display it. That would not require any additional communication between the browser and the server, just do it at the end of your /lib/message_center.php script for the messages you are displaying at that moment.
Set the href attribute for your X produced by php like href="javascript:killbox(5);" and give your div a unique id (i.e.id="boxtokill5"). Then you could use something like this:
function killbox(id){
$("#boxtokill"+id).hide();
var packet = {};
packet.clickedlinkid = id;
$.get("destination.php",packet,function(data){
// data = Response (output) from script
});
}
The destination.php receives the ID by $_GET['clickedlink'].
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