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 !
Related
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";
?>
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.
Dynamic HTML page with PHP that has 12 images in first load and theres load more button to load another 12 image on click event,
Now the idea of this code to reduce page load time, So every things is going well but i have event onclick for each image loaded in this html page now how i can append new 12 images over the first 12 and so on and keep the event foreach image still running
here's the code i use ,
php to get first 12 images
$results_per_page = 12;
$page = 1;
$start = ($page-1)*12;
$data['styles'] = $this->Discover_model->get_more_styles($start);
html handling images as
<div class="product-list grid column3-4-wrap" id="interiors_samples" >
<?php if($styles):?>
<?php foreach ($styles as $style) {?>
<div class="img_card col">
<div class="sampleFind">
<img class = "Int_img" id="<?php echo $style->id?>" src="<?php echo base_url();?>include/int_imgs/ <?php echo $style->img_name;?>" alt="product-image">
</div>
</div>
<?php }?>
<?php endif;?>
</div>
jquery function to load more images over firs image
$('#load').click(function(){
var click_time = 0;
if(click_time === 0){
var page = 2;
}
click_time++;
$.ajax({
type:'POST',
data:{pagenum:page},
url:'<?php echo base_url(); ?>Process/getInterImgs',
success:function(data) {
$('#interiors_samples').append(data);
page = page + 1;
}
});
});
And this function get another 12 of images and return result to post call above
public function getInterImgs() {
$page = $_POST['pagenum'];
$this->load->model('Discover_model');
$results_per_page = 12;
$start = ($page-1)*$results_per_page;
$data['styles'] = $this->Discover_model->get_more_styles($start);
$styles = $data['styles'];
foreach ($styles as $style ){
$loadimgs = '<div class="img_card col">
<div class="sampleFind">
<img class = "Int_img" id="'.$style->id.'" src="'.base_url().'include/int_imgs/ '.$style->img_name.'" alt="product-image">
</div>
</div>';
}
print_r($loadimgs);exit();
return $loadimgs;
}
Now i need to know what is happened after append images to html Dom because the jquery method for each image works fine for first 12 images and doesn't work for loaded image known the id's name is the same with first 12 item
Any help please
Try this :
$(document).on("click", "#load", function () {
// your code
})
I've searched everywhere for a method where a page can reload automatically for every x seconds without actually reloading the page's contents, I have php code(includes some html) which updates my database table whenever a new user joins the page. However this only works once.
PHP CODE
<?php
$userOn5 = "SELECT * FROM `usersOn` WHERE name = '$username'";
$query4 = mysql_query($userOn5) or die (mysql_error());
while ($row = mysql_fetch_array($query4)) {
// Gather all $row values into local variables for easier usage in output
$timenow = $row["time"];
}
$user = "SELECT * FROM `user`";
$query3 = mysql_query($user) or die (mysql_error());
while ($row = mysql_fetch_array($query3)) {
$usernow = $row["name"];
}
$secs = time() - $timenow;
mysql_query("UPDATE user SET name = '$user'");
if ($username == $usernow) {
?>
<div id="container" style="display:none;">
I've attempted using meta tag but that reloads the entire content, I've attempted moving the entire php code to a separate php file and tried loading it inside a div called 'show' in the page:
var auto_refresh = setInterval(
function ()
{
$('#show').load('registeruser.php').fadeIn("slow");
}, 10000); // autorefresh the content of the div after
//every 10000 milliseconds(10sec)
Basically what I'm trying to do is rerun the php code every 10 seconds. Help?
Quite likely your issue is due to browser cache. You can use the following workaround -- that's actually what ajax does when you use cache: false:
$(function() {
var auto_refresh = setInterval(function () {
var t = Date.now();
$('#show').load('registeruser.php?t=' + t);
$('#container').fadeIn("slow");
}, 10000);
});
UPDATE
Alternatively, you can use the following:
$(function() {
var auto_refresh = setInterval(function () {
var t = Date.now();
$('#show').load('registeruser.php?t=' + t).find('> div').fadeIn("slow");
}, 10000);
});
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