currently I am working on a online quiz platform and I want to show a quiz timer.first I use javascript to show timer but problem is that when user refresh a page or goes back the quiz timer start again form start so I want to use session variable time to show quiz timer. and I set this session variable when user start the quiz. but my code is not working properly. here is my code:
`<?php
include_once 'dbConnection.php';
session_start();
if(!(isset($_SESSION['email']))){
header("location:login.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script>
// timer will start when document is loaded
$(document).ready( function () {
startTest();
});
var si;
function timer(){
<?php $_SESSION['time']-= 1000; ?>
var count="<?php echo $_SESSION['time']; ?>";
var min = Math.floor(count / (60 * 1000));
var sec = Math.floor((count - (min * 60 * 1000)) / 1000);
min = (min < 10)?'0'+min:min;
sec = (sec < 10)?'0'+sec:sec;
if (count <= 0){
document.getElementById('duration').innerHTML ="Time Up";
clearInterval(si);
// submit my quiz.
}
else {
document.getElementById('duration').innerHTML = "00:" + min + ":" + sec;
}
}
function startTest(){
si = setInterval( "timer()", 1000);
}
</script>
</head>
<body>
<p id="duration" >show time</p>
</body>
</html>`
this code is giving some unexpected error or doesn't work properly.
Remove the double quotes if its an integer
var count=<?php echo $_SESSION['time']; ?>;
What i understand from your description is that you need time duration from server side. so that if any one refresh the browser don't restart the timer from the beginning .
You need to calculate the time duration on server side. That can be achieved by using ajax call.
<?php
session_start();
$_SESSION['start_time'] = time();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
// timer will start when document is loaded
$(document).ready( function () {
setInterval(() => {
$.ajax({
url:"timer.php", //path to your file
success:function(data) {
// do your code here
$('#duration').text(data);
}
});
}, 1000);
});
</script>
</head>
<body>
<p id="duration" >show time</p>
</body>
</html>
Create new php file for calculating time timer.php
<?php
session_start();
$start_time = $_SESSION['start_time']; // start time;
$from_time = time(); // current time;
$minutes = round(abs($start_time - $from_time) / 60);
$seconds = abs($to_time - $from_time) % 60;
echo "$minutes minutes & $seconds seconds";
?>
Related
i am trying to send an auto generated mail for wedding event so i have an countdown timer using java script and i want to send a reminder before a day . i tried in php and java script but i am not getting expected output.
Tried below code using java script, but it is not sending /displaying my message on the console
<!DOCTYPE html>
<html>
<p id="demo"></p>
<style>
p {
text-align: center;
color: #7FFF00;
font-size: 50px;
margin-top: 0px;
}
</style>
<script>
// Set the date we're counting down to
var countDownDate = new Date("April 3, 2019 10:30:01").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "Today is the wedding";
}
var myvar=20;
while(distance==myvar){
document.getElementById("demo").innerHTML = "Reminder";
<?php
//to send an wedding reminder
include "Sendmail.php"
?>
}
}, 1000);
</script>
</html>
Hence i tried with below Php using page auto refresh option:but it is not working as exected-------------------------------------------------------------------------------
<!DOCTYPE html>
<html>
<body>
<?php
echo "Today is " . date("l");
//date_default_timezone_set('America/New_York');
//timezone_name_from_abbr('IHST',19800) for Asia/Colombo
//set the timezone for ist:
date_default_timezone_set('Asia/Kolkata');
$today = date("Y-m-d H:i:s");
$date = "2019-02-26 07:43:16 ";
$tilldate = "2019-02-26 07:43:50 ";
echo $today;
do {
$page = $_SERVER['PHP_SELF'];
$sec = "6";
//echo "Watch the page reload itself in 3 second!";
}while ( $date<=$today)
echo" when satisfied call my function and come out of loop";
break;
//if($today < $date ||$today < $tilldate){
//echo "Watch the page reload itself in 3 second!";
//break;
// echo "Watch the page reload itself in 3 second!";
//include 'FetchData.php';
//}
?>
<html>
<head>
<meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
</head>
<body>
<?php
echo "Watch the page reload itself in six second!";
?>
</html>
It will be very helpful if some one assist me on this.
If your goal is to build a site where people can enter a wedding date, and have it email them a reminder a set time before, you will need to store that data on a server somehow.
If you are familiar with NodeJS you could use it to set up a small app that keeps the wedding dates in memory, (though longer-term storage is safer), and then you can use something like Nodemailer to send the email once the time is reached.
However if you don't know NodeJS, using Javascript alone won't be enough - and you can't call PHP code with JS using an embed like you're doing. Keep in mind that PHP is rendered out before any Javascript is run, so JS can't directly call a PHP function. In order to get JS to communicate with PHP in most cases you'll want to make an AJAX call to a PHP script on your server.
So your front end will be a page that uses JS to send an AJAX request containing a wedding date to a separate PHP script on your server. That PHP script will then save that data to the server, using something like mySQL, (or in a pinch you can just use fwrite( ) to write to the local file structure, though a full database system is safer.)
Now you'll need a 2nd PHP script that checks the data every minute or so, and sends an email when a wedding date is close enough. However, you don't want to use auto-refresh to keep a PHP script running. Instead you'll want to set up a cron task that calls your PHP script however often you need it to.
So the elements you'll need are: 1) HTML page containing Javascript, which sends AJAX data to 2) A PHP script that saves that data to your server, and 3) A 2nd PHP script, called by cron, which checks the data and emails when necessary
On the other hand, if all you need is an email reminder for one specific wedding, you'd probably be better off scheduling it through your email client, or using something like IFTTT.
I have a code that is meant to refresh the page on the hour, every hour but it doesn't seem to execute...
This is the code:
<?php
date_default_timezone_set('Australia/Sydney');
$date = date("i:s");
list($cur_min, $cur_sec) = explode(':', $date);
$mins_left = ($cur_min == 59) ? 0 : 60 - $cur_min;
$secs_left = 60 - $cur_sec;
$time=($mins_left*60+$secs_left)*1000;
?>
<script type="text/javascript">
setInterval("refresh()",<?php echo $time; ?>);
function refresh(){
window.location = location.href;
}
</script>
I need it to run off the server clock too and not from when the user lands on the page.
Idealy, would be awesome if it could just refresh the content of every div labeled with the class named "locality"...
I would use DateTime in PHP and for easy convertion use timestamps.
$date = new \DateTime(strtotime(time()), new \DateTimeZone("Australia/Sydney")));
$date->add(new \DateInterval('PT1H'));
$time = $date->format('U') % 3600;
And for JS:
var time = (Math.round((new Date()).getTime() / 1000) % 3600);
if(time > <?= $time ?>){
var rtime = time - <?= $time ?>;
} else {
var rtime = <?= $time ?> - time;
}
setInterval(function(){
window.location.reload(1);
},rtime * 1000);
But im not sure why:
<meta http-equiv="refresh" content="3600">
Will not suffice as it will just refresh an hour later (and so on) of when the user enters the page, doesn't really matter what timezone.
Try this code for the JavaScript part:
function refresh(){
window.location.reload();
}
setTimeout(refresh, <?php echo $time; ?>);
I'm not sure if it will solve your problem, but I tried a few changes:
window.location.reload() is more explicit than window.location = location.href (which, by the way, could be simplified to window.location = window.location)
setTimeout instead of setInterval because if the refreshing fails again for some reason, you don't want to try refreshing again in
put the setTimeout call after the definition of the function to be sure that there isn't a problem with the function not being defined yet
Try it. If that code still doesn't work for you, try looking at your generated HTML and seeing what value for $time was printed. Also check the browser console for any errors.
By the way, the code would be clearer if you renamed the variable $time to $ms_until_start_of_hour.
Hey guys am really a noob in php...I just want to make a redirect after the session ends..So i have came to know that without js this cant be implemented..So i have modified the code with the help of my friends
<html>
<body>
<?php
session_start();
$_SESSION['logintime'] = time();
echo 'this page needs to be redirected in a minute'
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
$(function(){
var loginTime = <?php echo $_SESSION['logintime']; ?>
var testSession = setInterval(function(){
var currentTime = Date.now() * 1000;
if((currentTime - loginTime) > 60) { //here 60 denotes a minute
<?php session_start();
session_unset();
unset($_SESSION);
session_destroy();
?>
window.location.href = 'www.google.com'; // redirecting process
}
}, 1000);
});
</script>
</body>
</html>
The code runs without errors ..but it isnt redirecting after 60 seconds..
Any guides to make this code work correct would be really appreciated..Thanx
Try this, it goes in the section of your html:
Using html only
<meta http-equiv="refresh" content ="5; url=http://www.target.com/">
5 is the number of seconds. Now you can replace 5 with some PHP generated value.
<meta http-equiv="refresh" content ="<?php echo $limitTime(); ?>; url=http://www.target.com/">
If you want to do it in Javascript use following syntax
setInterval(function () {window.location.href = 'http://www.google.com'}, 60000)
In php you can use header method to redirect url
header("Location: http://www.google.com")
I have X tables on my php page. In each, i've timer. These timers doesn't have the same duration. I would like to know how to refresh these timers (separatly) with one JS/AJAX function.
timer.php (i can't post the real code, just an example to allow you to understand)
<?php
tab_number = X;
for ($i=0; $i<=X; $i++) {
$duration = MySQL query on duration with $i parameter. Return seconds for the timer.
$time_left = php function to change seconds to min:sec and to decrease $time_left each seconds
// just keep in mind that my timer is working, all of above is an example, my problem is on refresh.
echo '<table>';
echo '<tr>';
echo '<td><div id="rem_time'.$i.'">' . $time_left. ' left</div></td>';
echo '<tr>';
echo '<table>';
javascript function on same page :
<script type="text/javascript">
function refresh() {
$('#rem_time').load('time.php #rem_time');
}
setInterval('refresh()',1000);
</script>
I would like to know if it possible to use my JS script for each rem_time1, rem_time2, ..., rem_timeX separatly
You could use data attributes on each table and query a php script with your ajax call. Here's an example using two tables with different timer counts:
HTML
<div id="table1" class="container">
<table data-url="/path/to/script.php?table=1" data-timer="1000">
<!-- Table content -->
</table>
</div>
<div id="table2" class="container">
<table data-url="/path/to/script.php?table=2" data-timer="500">
<!-- Table content -->
</table>
</div>
JAVASCRIPT
// Here we select using the attribute, you could use a class or other
$('[data-timer]').each(function(){
$this = $(this);
$parent = $this.parents('div.container');
// Set interval will call the load function every x milliseconds
setInterval(function(){
// Now we use the table data attributes to load the
// correct data with the correct inteval
$parent.load( $this.attr('data-url'), function() {
console.log( "Load was performed." );
});
}, $this.attr('data-timer') );
});
PHP
$table = $_GET['table']
if($table == '1'){
// ouput table 1 html
}else{
// output table 2 html
}
I changed my code :
JAVASCRIPT
function timer(i, start_date, duration) {
setInterval(function() {
var date_now = Math.round(new Date().getTime() / 1000);
var rem_time = duration - (date_now - start_date);
// Times calculs
minuts = parseInt(rem_time / 60);
seconds = parseInt(rem_time % 60);
if (rem_time >= 0)
document.getElementById("rem_time"+i).innerHTML = minuts + ":" + seconds;
}, 1000);
}
PHP/HTML (mixed but syntax error)
<table>
for ($i=1; $i<X; $i++) {
<tr><td>
<div id="rem_time".$i.> <script> timer($i, '14:30:25', 600);</script></div>
</tr></td>
}
</table>
and it works :)
Thx all !
as the title says, is it possible to refresh a div without another html or php page inside of the div?
for example this is what can be done using javascript:
$(document).ready(function () {
$('#mydiv').delay(10000).load('page.php');
});
My Div shows/holds a data which is pulled from the mysql database and it doesn't have page.php inside it.
I've searched for this and all the results were similar to the one i posted above!
is this even possible and if so how?
EDIT:
the data that currently is displayed in the DIV is the $end_time for an item. the $end_time is basically a datetime which is stored in the mysql database. the $end_time already is ticking (a countdown timer using javascript). There is button which whenever pressed, 1 minute Will be added to the $end_time in the mysql.
But when the button is pressed I need to refresh/re-load the page in order to be able to view the changes (in this case 1 minuted added to the countdown timer).
what I need to do is to reload the DIV once that button is pressed so all the users can see that 1 minute has been added to the countdown timer WITHOUT reloading or refreshing the page.
EDIT:
Here is my full code, this works as it should and it will pull the data from mysql database as it should so I have no problem with this part of the project:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php date_default_timezone_set('Europe/London'); ?>
<?php
session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database
include "config/connect.php";
$dynamicList = "";
$sql = "SELECT * FROM item ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$date_added = date("Y-m-d", strtotime($row["date_added"]));
$end_date = date("F d Y H:i:s T", strtotime($row["end_date"]));
$price = $row["price"];
$dynamicList .= '<div>' . $end_date . '
</div>';
}
} else {
$dynamicList = "No Records";
}
?>
<?php
$date = $end_date;
$exp_date = strtotime($date);
$now = time();
if ($now < $exp_date ) {
?>
<script>
// Count down milliseconds = server_end - server_now = client_end - client_now
var server_end = <?php echo $exp_date; ?> * 1000;
var server_now = <?php echo time(); ?> * 1000;
var client_now = new Date().getTime();
var end = server_end - server_now + client_now; // this is the real end time
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24
var timer;
function showRemaining()
{
var now = new Date();
var distance = end - now;
if (distance < 0 ) {
clearInterval( timer );
document.getElementById('countdown').innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor( (distance % _day ) / _hour );
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var countdown = document.getElementById('countdown');
countdown.innerHTML = '';
if (days) {
countdown.innerHTML += 'Days: ' + days + '<br />';
}
countdown.innerHTML += 'Hours: ' + hours+ '<br />';
countdown.innerHTML += 'Minutes: ' + minutes+ '<br />';
countdown.innerHTML += 'Seconds: ' + seconds+ '<br />';
}
timer = setInterval(showRemaining, 1000);
</script>
<?php
} else {
echo "Times Up";
}
?>
<div id="result"><div id="countdown"></div></div>
<?php echo $end_date; ?> </br>
<?php echo $dynamicList; ?>
<script src="ajax_link.js" type="text/javascript"></script>
<div id="ajaxlink" onclick="loadurl('timeadder.php')">Click here</div>
<input type="submit" name="ajaxlink" id="ajaxlink" value="Submit" onclick="loadurl('timeadder.php')"/>
and Here is the code for the page that will add the 1 minute to the database and this owrks fie as it should too:
timeadder.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php
session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database
include "config/connect.php";
$sql = "UPDATE item SET end_date = DATE_ADD(end_date,INTERVAL 1 MINUTE) WHERE id = 1;";
$query = mysqli_query($db_conx, $sql);
?>
All i need to do is to refresh the DIV countdown that holds the timer.
I hope someone now can help.
The question is unclear, but if your were trying to periodically load a php into a div it could be done with setInterval
setInterval(
function(){
$('#mydiv').load('page.php');
},10000);
EDIT:
Ok then Id suggest Jquery.get
setInterval(function(){
$.get('page.php',function(timerValue){
$('#mydiv').html(timerValue);
});
},1000);
Modified to integrate newly posted code in OP:
In your while{} statement, you are sticking div tags around the end date, but there is no easy way to identify which item's end date the div belongs to.
Suggestion:
$dynamicList .= '<div id="ed-' .$id. '">' . $end_date . '</div>';
That will create a uniquely named div around each end date. Now, you can access a specific end date via jQuery, thus:
$('#ed-3').html(newdata);
Also, shouldn't this:
<div id="result"><div id="countdown"></div></div>
<?php echo $end_date; ?> </br>
Be like this:
<div id="result"><div id="countdown"><?php echo $end_date; ?></div></div>
</br>
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var item_id = 0;
$(document).ready(function() {
$('#mybutt').click(function() {
item_id = $(this).attr('id').split('-')[1];
updateTimer();
});
}); //END $(document).ready()
function updateTimer() {
$.ajax({
type: 'POST',
url: 'getenddate.php`,
data: `item=` + item_id,
success: function(fromPhp) {
$('#countdown').html(fromPhp);
//or, to change this item's end date as echoed out from $dynamicList:
//$('#ed-' + item_id).html(fromPHP);
} //END success fn
}); //END AJAX code block
adder = 0;
} //END updateTimer fn
</script>
</head>
<body>
<div id="countdown"></div>
<input id="item-12" type="button" value="Add One Minute">
</body>
</html>
PHP: getenddate.php
<?php
//item is NAME of var being posted over (key),
//item_id is the var contents on the client side ONLY
//$_POST['item'] is var contents (value) as it arrives on PHP side
$itemid = $_POST['item'];
// ** FIXME the query contains a SQL injection vuln,
// ** please untaint $itemid before using
//code to return current time value from database - runs every time
$end = mysql_result(mysql_query("SELECT `end_date` FROM item WHERE `id` = '$item' "), 0);
echo $end;
If I understood you right, you want to change the content of a DIV, no matter what is inside. This can be accomplished like this:
in the HTML you have something like:
<div id="mydiv">My old content, no sites here</div>
An in the JS(jQuery enabled) you do (for example in the ready function):
$(document).ready(function () {
$('#mydiv').html("This content is brand new");
});
jsFiddle of the code above
The .html() function deletes the old content of that tag and replaces it with new content.
If you, for example, want to show the current seconds, you can do as follows:
$(document).ready(function () {
setInterval(function(){
// change time
$('#mydiv').html("Seconds: "+ new Date().getSeconds());
},1000);
});
jsFiddle of the code with counter
This should be almost exactly what you are looking for (untested):
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var adder = 0; //Global var -- outside document.ready
$(document).ready(function() {
$('#mybutt').click(function() {
adder++;
updateTimer();
});
}); //END $(document).ready()
function updateTimer() {
$.ajax({
type: 'POST',
url: 'myphpprocessor.php',
data: 'addval=' + adder,
success: function(fromPhp) {
$('#theTimer').html(fromPhp);
} //END success fn
}); //END AJAX code block
adder = 0;
} //END updateTimer fn
</script>
</head>
<body>
<div id="theTimer"></div>
<input id="mybutt" type="button" value="Add One Minute">
</body>
</html>
PHP: myphpprocessor.php
<?php
$howmuch = $_POST['addval'];
if ($howmuch > 0) {
//code to update database by the amount
// - only runs if howmuch has a value
}
//code to return current time value from database - runs every time
$thetime = mysql_query('SELECT etc etc etc');
echo $thetime;
Notes:
The database only needs to store the number of minutes to be added to the current time
Your PHP code can then:
(a) Query the DB for number of mins to add: $num_mins_to_add
(b) Create a new date object with current time
(c) Add the $num_mins_to_add to (b)
(d) ECHO back the value