PHP AJAX Comet with MySQL select record - php

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>

Related

"Automatically update time in PHP using Ajax - display

I wish to show the current local time on my weather web site.
This is the code that I use from a query :"Automatically update time in PHP using Ajax" posted 2 years ago
<?php
echo "<html>
<head>
<title>Realtime clock</title>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<script src='http://code.jquery.com/jquery.js'></script>
<script>
$(document).ready(function(){
setInterval(_initTimer, 1000);
});
function _initTimer(){
$.ajax({
url: 'timer.php',
success: function(data) {
console.log(data);
data = data.split(':');
$('#hrs').html(data[0]);
$('#mins').html(data[1]);
$('#secs').html(data[2]);
}
});
}
</script>
</head>
<body>
<span id='hrs'>0</span>:<span id='mins'>0</span>:<span id='secs'>0</span>
</body>
</html>"; ?>
<?php date_default_timezone_set("Australia/Brisbane");
echo "Current Time: ". date("H:i:s"). " AEST";
?>
This is what I getwhen I run this:
17:05:10 Current Time: 17:01:30 AEST
What I am aiming to achieve is:
Current Time: 17:05:10 AEST with the time updating every second.
Is there some addition that I need to make in the final echo statement? Or do something else
please help
Thanks
To show current time every second you could use jquery to show time, instead of running ajax on server for every second
Try this:
var nIntervId;
function updateTime() {
nIntervId = setInterval(flashTime, 1000);
}
function pad(n) { return ("0" + n).slice(-2); }
Number.prototype.pad = function (len) {
return (new Array(len+1).join("0") + this).slice(-len);
}
function flashTime() {
var now = new Date();
var h = now.getHours().pad(2);
var m = now.getMinutes().pad(2);
var s = now.getSeconds().pad(2);
var time = h + ' : ' + m + ' : ' + s;
$('#my_box1').html(time);
}
$(function() {
updateTime();
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<div id="my_box1">
</div>
I assume you have made a separate timer.php file just to echo server time. As your current page is loading just once, the initial server time will not be updated that is your "current time value". Whereas the remaining DOM will be updated with the server time because of ajax code. If you want both times to be same you will have to reload the whole page which is not correct. Hence, I suggest you to display only one time which should be your ajax result.
timer.php:
<?php
date_default_timezone_set("Australia/Brisbane");
echo date("H:i:s");
?>

show realtime total visitors

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...

javascript countdown update db and refresh

can someone please help me with js/ajax countdown i want a countdown timer to 10 sec then update the database and refresh the page once it hits to 0.
i'm not really good with javascript/ajax, here is what i got so far:
var ss = 10;
function countdown() {
ss = ss-1;
if (ss<0) {
var url='update.php?countdown='+countdown;
}
else {
document.getElementById("countdown").innerHTML=ss;
window.setTimeout("countdown()", 1000);
}
}
<span id="countdown" style="color:green;">10</span>
and update.php file, witch works fine:
if (isset($_REQUEST['countdown'])) {
mysql_query("INSERT INTO num (id, ad, active)
VALUES ('1', 'Test',1)") or die(mysql_error());
}
and also this is what i found http://pastebin.com/Qwz3Zqtt , works fine but i don't know how to put them together.
any helps would be appreciated.
Thanks
You're going to want to learn basic ajax to process the database request. jQuery has a very easy to use implementation.
The basic code could be something like:
<script>
function updateTimer(seconds){
var countdown = document.getElementById('countdown');
countdown.innerHTML = "Please wait " + seconds + " seconds.";
}
var timer = function() {
var seconds = 10;
var interval = setInterval(function(){
if (seconds <= 0){
countdown.innerHTML = "Finished.. Updating Database";
// AJAX request here
clearInterval(interval);
}else{
updateTimer(seconds);
--seconds;
}
}, 1000);
updateTimer(seconds);
--seconds;
}
document.getElementById('start').addEventListener('click', timer);
</script>
<div id="countdown"></div>
<button id="start">Click Me</button>
Here's a fiddle
Use jQuery ajax
Simplest example:
if (ss<0) {
$.ajax('update.php?countdown='+countdown);
}

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.

Browsed Time Problem

I want to display the browsed time of a user, But when i refresh it, it will be again start from 0:0:0.
How can it handle?
<?php
$total_mints=($live_match['match_name']) * (60);
?>
<script language="javascript">
display_c(<?=$total_mints?>,'ct');
</script>
<script type="text/javascript">
function display_c(start,div){
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh=1000; // Refresh rate in milli seconds
if(window.start >= end ){
mytime=setTimeout("display_ct('"+div+"')",refresh)
}
else {alert("Time Over ");}
</script>
Once the time is over, you could set a cookie to 'Time Expired'... When the page is loaded, if the cookie is 'Time Expired' then you can display the 'Time Over' alert. You can also use the cookie to keep track of accumulated browsing time.
Edit - added some specifics... but I think you'll have to think about this some more.
Basically, you want to use JS to write the cookie as the user uses the page, and you want to use PHP to read the cookie when the page is loaded. You can use the cookie to either only track whether time is up, total accumulated time, or both. I think you'd want to renew the cookie every minute or so?
It's going to look SOMETHING like this - this code just shows how to keep track of whether time has expired or not with a cookie, not accumulated time.
<?php
$total_mints=($live_match['match_name']) * (60);
// check for cookie and only proceed if it is not expired
// can also use cookie to keep track of total accumulated number
// of minutes between session
if ($_COOKIE["yourMints"] != "expired")
{
?>
<script language="text/javascript">
display_c(<?php echo $total_mints; ?>,'ct');
</script>
<script type="text/javascript">
function display_c(start,div)
{
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh=1000; // Refresh rate in milli seconds
if(window.start >= end )
{
mytime=setTimeout("display_ct('"+div+"')",refresh)
} else
{
alert("Time Over ");
// set cookie to expired
document.cookie = "yourMints=expired";
}
}
</script>
<?php
} else // What follows is what happens if cookies IS expired
{
?>
<script type="text/javascript">
alert("Time Over ");
</script>
<?php
}
?>
Here is a good JS cookies tutorial:
http://www.quirksmode.org/js/cookies.html
Here is using $_COOKIE to read cookies with PHP
http://php.net/manual/en/reserved.variables.cookies.php
EDIT: Added in JQuery example after seeing PlagueEditor's example.
Nice script PlagueEditor. Thought I'd try the same thing w/ JQuery for fun.
JQuery has a simple little cookie plugin... only 40 lines of code or so.
Here's a page with a cookie stored timer and a timeout of 10 seconds with a possible reset:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Time Spent on Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="PATH-TO-YOUR-JQ-DIRECTORY/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="PATH-TO-YOUR-JQ-DIRECTORY/cookie.js"></script>
<script type="text/javascript">
<!--
$.myTimer =
{
timeLimit: 10,
displayTime: function ()
{
if ($.myTimer.time < $.myTimer.timeLimit)
{
$("#timeHere").html($.myTimer.time);
$.cookie('yourMints', $.myTimer.time, { expires: 7});
++$.myTimer.time;
$.myTimer.toggle = setTimeout("$.myTimer.displayTime()",1000);
} else
{
$("#page").html('<h1>Time expired</h1>');
}
}
}
// When the page is ready ==================================================
$(document).ready(function()
{
// Read time spent on page cookie. Set it, if it doesn't exist.
if (!$.cookie('yourMints'))
{
$.cookie('yourMints', '0', { expires: 7});
}
$.myTimer.time = $.cookie('yourMints');
// Start timeer
$.myTimer.displayTime();
// Reset the timer
$("#reset").click( function()
{
$.cookie('yourMints', '0');
window.location.reload();
});
});
// -->
</script>
</head>
<body>
<div id="page">
<h2>Your total time here: <span id="timeHere"></span></h2>
You can only look at this page for 10 seconds.
</div>
<input id="reset" type="button" value="Reset Timer" />
</body>
</html>
Below is a solution for keeping track of the browsed time, even with refreshing. It gets the date when the page loads and every second subtracts that date from the given date. The date is then displayed in the span. The page should work by itself. I hope this is what you were looking for, or at least helps. Two functions were W3Schools examples*.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
/**
* getCookie and setCookie were taken from http://www.w3schools.com/JS/js_cookies.asp.
*/
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
var totalTime=0;
var storedTime=getCookie("storedTime");
if(storedTime.length == 0){
//If it doesn't exist..
storedTime=0;
}else{
storedTime=parseInt(storedTime);
totalTime=storedTime;
}
function updateTime(){
totalTime+=1000;
document.getElementById("duration").innerHTML= Math.ceil(totalTime / 1000);
}
onbeforeunload = function(){
setCookie("storedTime",totalTime,3);
}
setInterval(updateTime, 1000);
</script>
Your total time here: <span id="duration"><script type="text/javascript">document.write( Math.ceil(totalTime / 1000));</script></span> seconds...
</body>
</html>

Categories