show realtime total visitors - php

I tried to show real time visitors visit(ed) the site. Below is my PHP file named getTotalVisitors. In the php file the uniquevisitors are showing well.
include 'common.php'; //get database connection
$query = "SELECT SUM(uniquevisitors) as uniquevisitors FROM " . $DBPrefix . "currentaccesses";
$params = array();
$db->query($query, $params);
while ($new = $db->fetch())
{
$uniquevisitors = $new['uniquevisitors'];
}
echo "visitors until now: " . $uniquevisitors . "<br>";
When i try to get it real time with the update and setInterval function with the below script, I cannot get it working. Anybody gives me the right direction/solution ?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
function updategetTotalVisitors()
{
$('#datashow').load('getTotalVisitors.php');
}
updategetTotalVisitors(); //set the datacount as soon as the page is loaded
setInterval( "updategetTotalVisitors()", 10000 ); //update the datashow every 10 seconds
});
</script>
<p>Visitors until now:</p>
<div id = "datashow"></div>

First of all, the function parameter of setInterval must be unquoted and without parenthesis:
setInterval( updategetTotalVisitors, 10000 );
Then, you have to declare updategetTotalVisitors outside $(document).ready scope and to assign the returned value of setInterval to a variable:
<script type="text/javascript">
var repeatFunction;
function updategetTotalVisitors()
{
$('#datashow').load( 'getTotalVisitors.php' );
}
$(document).ready(function()
{
updategetTotalVisitors();
repeatFunction = setInterval( updategetTotalVisitors, 10000 );
});
</script>
The script above works, for me. Obviously I have tested it with fake getTotalVisitors.php, but you say that your php works, so...

Related

i want to get data from php file with ajax once per 5 min

I'm get data from excel file with php.After this data get from php file with ajax.In fact, I want to get data from excel file once per 5 min and print page.How can i do?
data.php
include "Classes/PHPExcel/IOFactory.php";
try {
$url="https://docs.google.com/spreadsheets/d/1ngOuUvGk07r69HEonmYdjl9En1F1COAB8fAhNXNT1Y8/pub";//Bu url 'i load'ın içine girdiğimde File not exist hatası veriyor.Ben localde denemek için aşağıdak inputfile .
$inputFile = 'a.xlsx';
$objPhpExcel = PHPExcel_IOFactory::load($inputFile);
$rows = $objPhpExcel->getActiveSheet()->toArray(null, true, true, true);
$i=0;
$data_en=array();
$data_tr=array();
$word=array();
foreach ($rows as $row)
{
$i++;
$data_en[$i] = $row['C'];
$data_tr[$i]= $row['D'];
echo $data_en[$i];echo "<br>";
}
}
catch(PHPExcel_Exception $e)
{
echo $e->getMessage();
}
index.html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.get("data.php", function(data){
$('#container').html(data);
});
});
</script>
<body>
<p id="container"></p>
</body>
You need to use setInterval() javascript function and set it to 5 minutes.
The JavaScript setInterval() function can be used to automate a task
using a regular time based trigger.
also you can clear scheduled work by clearInterval()
it is a native JavaScript function.
var duplicateWork = setInterval(function() {
// Do something every 1 seconds
}, 1000);
// To cancel scheduled work use similar code
clearInterval(duplicateWork);
look at the example :
var l = $('#list');
var duplicateWork = null;
var seconds = 1000 * 2;//2 second
$('#start').click(function(){
$('#title').html('Start : add item once per 2 second');
duplicateWork = setInterval(function() {
// Do something every 2 seconds
l.append('<li>duplicate work</li>');
}, seconds);
});
$('#stop').click(function(){
$('#title').html('Stop');
clearInterval(duplicateWork);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">Start</button>
<button id="stop">Stop</button>
<h3 id="title"></h3>
<hr />
<ul id="list">
</ul>
In your case , you can use similar code
$(document).ready(function()
{
var seconds = 1000 * (60 * 5);//5 minute
var refreshId = setInterval( function() {
$.get("data.php", function(data){
$('#container').html(data);
});
}, seconds);
});

Ajax with jquery to set time interval

I'm working on a notification message i want to load new message from a page call check_new-reply.php in every 10 second using Ajax and Jquery but my code is not showing anything i don't know what the error is please can someone help me out?
<script>
$(document).ready(function(){
$(function(){
var timer = 10;
var test = "";
function inTime(){
setTimeOut(inTime, 1000);
$("#timer-u").html("Time refreshing"+timer);
if(timer == 8){
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
})
timer = 11;
clearTimeout(inTime);
}
timer--;
}
inTime();
});
});
</script>
Here is PHP
<?php include($root . '_inc/Initialization.php');?>
<?php require_once("_inc/dbcontroller.php"); $db_handle = new DBController();?>
<?php
$users = $_SESSION['username'];
$newquery = "SELECT * FROM blog_post
INNER JOIN replys
ON blog_post.UserName = '$users'
WHERE replys.read = 0
ORDER BY rtime";
$newhisory = mysql_query($newquery);
while($newrow = mysql_fetch_array($newhisory)){
echo '<div class="fnot">'.htmlentities($newrow['blog_title']).'';
echo '<span class="ttcredit"><font color="darkgreen">94</font> </span> <a class="reqttag reqttag2" href="#">No</a> ';
echo '</div>';
echo '<input type="hidden" id="unr" name="unr" value="'.$newrow['BID'].'"/>';
}
?>
If you just want to call it every 10 seconds, use 10000 milliseconds in the setTimeOut . Also, it is best to call again the function only when the previous Ajax call is done:
$(document).ready(function(){
$(function(){
var test = "";
function inTime(){
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
setTimeout(inTime, 10000);
});
}
inTime();
});
});
To call any function with some intervals you will have to use
<script>
$(document).ready(function(){
window.setInterval(function(){
myAjaxCall();
}, 10000);
});
function myAjaxCall() {
alert("Hi");
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
});
}
</script>
window.setInterval will call your function on every 3 seconds with above code, and will generate an alert message,
what you have to do is set your ajax code in a function and use above method, change 3000 to 10000 and your ajax call will defiantly work with every 10 seconds,
This is the code which will call our javascript function on every 10 seconds,
just copy it and check it, you will get an idea, also i have included the jquery as we have discussed.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
</body>
<script>
$(document).ready(function(){
window.setInterval(function(){
myAjaxCall();
}, 3000);
});
function myAjaxCall() {
alert("Call your Ajax here");
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
});
}
</script>

PHP AJAX Comet with MySQL select record

I would like to implement comet with records fetch from PHP
My PHP will do the following.. at a page call getlog.php
$sql = "select log_description,log_time from log ORDER by log_time DESC";
$result=mysql_query($sql);
if($result == false)
{ die("unable to fetch records."); }
while ($row = mysql_fetch_assoc($result)) {
$result_output[] = $row;
}
$counter = 1;
foreach($result_output as $row)
{
echo $counter . ". " $row[log_description];
$counter++;
}
If there is new log, I would want to echo it out in viewlog.php
So it would appear like this in viewlog.php
1. Customer 1 logged in at 12:05.
maybe 5 minutes later
1. Customer 2 logged in at 12:10
2. Customer 1 logged in at 12:05
It maintain a maximum of like lets say 15 records.
The data is fetch from PHP, I read the way to do it is something call "comet" but I just want a simple database fetch which auto refresh e.g every 10 seconds to see if there is new record added to the database and append it to the div.
Is there a easy way to achieve this using AJAX and PHP and not using comet.
Thanks for all the help, greatly appreciate !
Did the following code changes
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
show_log(){
var lnk = "fetchlog.php";
$.ajax({url:lnk,success:function(result){
$("#log_div").html(result);
}});
}
window.setInterval(function(){
show_log();
}, 10000);
</script>
</head>
<body>
<div id="log_div"></div>
</body>
</html>
Whats wrong with my code as it doesn't fetch from fetchlog.php
fetchlog.php echo something like this
1. Acct_1 logged to the system.
2. Acct_3 logged in to the system.
3. Acct_2 logged in to the system.
4. Assign permissions on Acct_1.
5. Delete record on table building with id 80
jsFiddle
Yes you can use ajax for this and simply update a div in your html.
You need to have jquery linked in order to use the below code.
show_log(){
var lnk = "link to the viewlog.php file";
$.ajax({url:lnk,success:function(result){
$("#log_div").html(result);
}});
}
Run the show_log() function every x number of mins.
Have your viewlog.php show the last x number of records in the descending order of time.
You can update your sql to look like
$sql = "select log_description,log_time from log ORDER by log_time DESC LIMIT 5 ";
You can use the below inside your javascript to run the function every x number of seconds. In this every 10 seconds.
window.setInterval(function(){
show_log();
}, 10000);
the 10,000 is in miliseconds
----- Try the below
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
http = getHTTPObject();
function getHTTPObject(){
var xmlhttp;
if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){
try {
xmlhttp = new XMLHttpRequest();
}catch(e){
xmlhttp = false;
}
}
return xmlhttp;
}
function show_log(){
var url = "viewlog.php";
http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function handleHttpResponse(){
if(http.readyState == 4){
document.getElementById('log_div').innerHTML = http.responseText;
}
}
setInterval ( "show_log()", 5000 );
</script>
</head>
<body>
<div id="log_div"></div>
</body>
</html>

javascript timer not counting down when retrieving time from db

I am trying to follow a jsfiddle example to create a time in javascript:
http://jsfiddle.net/g3rRJ/
Now obviously the timer in the jsfiddle works fine. But the issue I have is that the time which the timer starts from comes for a mysqli/php variable where it retrieves the time from the db.
So except for:
<span id="countdown">01:30:10</span>
I have to have it as:
echo "<p><span id='countdown'>" . $dbSessionDuration . "</span></p>";
AND
except for:
var time = "01:30:10",
I have to have it as:
var time = <?php echo json_encode($dbSessionDuration); ?>,
Now I am getting no errors but what is happening is that the timer is not doing a count down. My question is why is it not counting down? An example of the time from the variable could be 01:00:00.
Below is the code for the function:
echo "<p><span id='countdown'>" . $dbSessionDuration . "</span></p>";
...
<script type="text/javascript">
(function(){
$(document).ready(function() {
var time = <?php echo json_encode($dbSessionDuration); ?>,
parts = time.split(':'),
hours = +parts[0],
minutes = +parts[1],
seconds = +parts[2],
span = $('#countdown');
function correctNum(num) {
return (num<10)? ("0"+num):num;
}
var timer = setInterval(function(){
seconds--;
if(seconds == -1) {
seconds = 59;
minutes--;
if(minutes == -1) {
minutes = 59;
hours--;
if(hours==-1) {
alert("timer finished");
clearInterval(timer);
return;
}
}
}
span.text(correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds));
}, 1000);
});
});
</script>
Change this:
});
});
</script>
to this:
});
})(); // ← note the extra parentheses
</script>
so that you actually call your anonymous function. (Alternatively, you can simply remove its (function(){ and }); entirely. There's no reason for this code to be in a function at all.)
I don't know if this was a mistype but I was able to run this code by adding $, $(function(){, at the first part of your anonymous function. I'm assuming your value from the db comes in as hours:mins:secs. I'm not sure why Fiddler ran but I had to add that to get it to work in my environment.

how to get div's text to a variable

what I mainly want to do is to get the div's content and pass it in a variable. To explain what I have done until now :
I have my php file that contains the code :
<?php
$connect = mysql_connect("localhost", "...","...") or die("Could not connect to the database.");
mysql_select_db("...") or die("Could not find database <...>");
$query = mysql_query("SELECT id FROM datainput WHERE id>=ALL(SELECT id FROM datainput)") or die("Query could not be executed");
$row = mysql_fetch_assoc($query);
echo $row['id'];
?>
In my index.php file I have written the following script :
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("document").ready( function(){
//setInterval("checkForNewData()", 1000); //30 Minutes = 1800000 Milliseconds
checkForNewData();
});
function checkForNewData(){
$("#lastid").load("lastData.php");
var mydata = $("#lastid").text();
}
</script>
In my html tag I have a div with id="lastid".
With the code below :
var mydata = $("#lastid").text();
I want to keep the current text of lastid div, so I can later compare it with another.
As I have read here, this should have done mydata="6" (is the current result)?
What am I doing wrong?
Can anyone help? Pleaseee...
You need to wait for the load to have finished. This is done by using a callback function like so:
<script type="text/javascript">
$("document").ready( function(){
//setInterval("checkForNewData()", 1000); //30 Minutes = 1800000 Milliseconds
checkForNewData();
});
function checkForNewData(){
$("#lastid").load("lastData.php", function(){
var mydata = $("#lastid").text();
});
}
</script>
Please see the jQuery API docs for more information: http://api.jquery.com/load/
Essentially, the second argument of the load function can be a function. If it is, then whatever code is in that function will be executed when the load has completed.

Categories