here's my script , it's a combined php and javascript
<?php
$countdown = strtotime("22:00") - time();
$itemtime = "22:00";
$realtime = substr(date('H:i'),0,5);
?>
<script>
var itemtime = "$itemtime";
var countdown = '$countdown';
var url = "$redirectpage";
var realtime = "$realtime";
// HOW WILL I ADD AN IF STATEMENT WITH THE SETTIMEOUT FUNCTION
// WHEREBY, if(realtime == itemtime) ..that's the only time the
// redirection should occur
setTimeout(function(){
location.href='$redirectpage';
},countdown * 1000);
</script>
<?php
$countdown = strtotime("22:00") - time();
$itemtime = "22:00";
$realtime = substr(date('H:i'),0,5);
?>
<script>
var itemtime = "<?php echo $itemtime;?>";
var countdown = '<?php echo $countdown;?>';
var url = "$redirectpage";
var realtime = "<?php echo $realtime;?>";
// HOW WILL I ADD AN IF STATEMENT WITH THE SETTIMEOUT FUNCTION
// WHEREBY, if(realtime == itemtime) ..that's the only time the
// redirection should occur
setTimeout(function(){
if(realtime == itemtime) location.href='$redirectpage';
},countdown * 1000);
</script>
Assuming $redirectpage is set in JavaScript and not PHP. If it is set in PHP, you'll need to assign it as I did above.
I ended up with my own solution,i place this inside the setTimeout function
if(countdown < 0) setTimeout("location.reload(true);",1000); location.href= "$redirectpage";
Related
I have this piece of JS code:
<script type="text/javascript">
var counter = 0;
function myFunction() {
counter++;
document.getElementById('countervalue').innerHTML = counter;
}
</script>
Which plusses a number with 1 everytime a button is pressed.
The variable "counter" decides what number to start with when the page is loaded.
This number is currently 0. But it is supposed to be a number from the database. So I made a database connection using PHP and I now have the database number in a PHP variable. However, how do I implement it on the JS script? I have tried this:
<script type="text/javascript">
var counter = $clicks;
function myFunction() {
counter++;
document.getElementById('countervalue').innerHTML = counter;
}
The variable $clicks is the number from my database that is supposed to be the starting number when clicking the button.
I tried this as well, with no luck:
var counter = <?php $clicks ?>;
You're close. You're just forgetting to echo your variable's content:
var counter = <?php $clicks ?>;
should be:
var counter = <?php echo $clicks ?>;
or, if you have short tags enabled:
var counter = <?= $clicks ?>;
var counter = <?=$clicks?>;
Remember the echo.
var counter = <?php echo $clicks; ?>;
function myFunction() {
counter++;
document.getElementById('countervalue').innerHTML = counter;
}
var counter = <?php echo $clicks; ?>;
Counter value should be assigned as
var counter = <?php echo $clicks ?>;
First i create an iframe for each url i have:
$url = array();
$url[] = 'example1.com';
$url[] = 'example2.com';
foreach($url as $u){
echo '<div class="frame_container">
<iframe "width="200" height="200" id="myiframe" src="http://www.'.$u.'"> </iframe>
<div class="loadingtime"></div>
</div>';
}
Then i have this javascript that should calculate the time before each frame starts loading, and the time after its loaded:
$(document).ready(function () {
load_time();
});
function load_time(){
var beforeLoad = (new Date()).getTime();
$('.frame_container iframe').on('load', function() {
var afterLoad = (new Date()).getTime();
var result = (afterLoad - beforeLoad) / 1000;
// beforeLoad = afterLoad;
$(this).parent().find('div.loadingtime').html(result);
});
}
My problem - the beforeLoad value is the same for all iframes. This value should be different for each frame because all fames dont start loading at the exact same time. Any suggestions?
write first div using php then remaining using your javascript code
var curFrame = 1;
var totalIFrame = 2;
var url = new Array('http://www.abc.com','http://www.xyz.com');
var beforeLoad = (new Date()).getTime();
var result = 0;
function addTime() {
var afterLoad = (new Date()).getTime();
result += ((afterLoad - beforeLoad) / 1000);
if(totalIFrame==curFrame){// number of iframe you will be loading
$(this).parent().find('div.loadingtime').html(result);
} else {
$('.frame_container').append('<iframe "width="200" height="200" id="myiframe" src="'+url[curFrame]+'" onload="addTime()"> </iframe>');
}
curFrame++;
}
Hello, I have some questions about how to protect this script from a straight url?
Members can just can go 'pages/map/hospital.php?status=healed' and voila, they don't need any wait time. How do I fix this?!
<?php
$status = $_GET['status'];
if(isset($status)){
session_start();
include('../../includes/core/member.php');
include('../../includes/core/config.php');
$member_id = $_SESSION['member_id'];
if($status == 'healed'){
mysql_query("UPDATE `members` SET `now_health` = '".$m_max_health."' WHERE `member_id` = '".$member_id."'");
}
}else{
include('includes/core/member.php');
}
$health = $m_max_health - $m_now_health;
$wait_time = $health * 5;
?>
<p id='health'>Healing (<?=$wait_time?>)</p>
<script>
$('#health').one('click', function() {
var count = <?=$wait_time?>;
countdown = setInterval(function(){
$("p#health").html(count + " seconds remaining!");
if (count == 0) {
$.ajax({
url: 'pages/map/hospital.php?status=healed',
success: function(data) {
clearInterval(countdown);
$("p#health").html('you have healed');
}
});
}
count--;
}, 1000);
});
</script>
Server-side validation is required.
I see that you already have the initial $wait_time in a variable. So you would want to leverage this and perform some basic math using a datetime function to ensure the count <= 0.
I have to create a countdown timer for a bidding website. The timer works properly when I put it outside of the while loop. However, id does not work inside the loop. What am I doing wrong? Here is my code:
<script>
var before=""
var current="ended"
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
function countdown(yr,m,d,id){
theyear=yr;themonth=m;theday=d
var today=new Date()
var todayy=today.getYear()
if (todayy < 1000)
todayy+=1900
var todaym=today.getMonth()
var todayd=today.getDate()
var todayh=today.getHours()
var todaymin=today.getMinutes()
var todaysec=today.getSeconds()
var todaystring=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec
futurestring=montharray[m-1]+" "+d+", "+yr
dd=Date.parse(futurestring)-Date.parse(todaystring)
dday=Math.floor(dd/(60*60*1000*24)*1)
dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1)
dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1)
dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1)
if(dday==0&&dhour==0&&dmin==0&&dsec==0){
document.getElementById(id).value=current
return
}
else
document.getElementById(id).value="Only "+dday+ " days, "+dhour+" hours, "+dmin+" minutes, and "+dsec+" seconds left "+before
setTimeout("countdown(theyear,themonth,theday,id)",1000)
}
</script>
<?php
include('../connection.php');
$rs = mysql_query("select * from datepic") or die(mysql_error());
if(mysql_num_rows($rs)){
while($row = mysql_fetch_array($rs))
{
$date = str_replace('-',',',$row['date']);
echo '<input type="text" id="'.$row['id'].'" size=80>';
?>
<script>
countdown(<?php echo $date.','.$row['id'];?>)
</script>
<?php
}
}
?>
change setTimeout with this:
setTimeout(function(){countdown(theyear,themonth,theday,id);},1000)
you can make your function to jQuery function like that:
jQuery.fn.countdown = function(yr,m,d){
$that = $(this);
theyear=yr;themonth=m;theday=d
var today=new Date()
var todayy=today.getYear()
if (todayy < 1000)
todayy+=1900
var todaym=today.getMonth()
var todayd=today.getDate()
var todayh=today.getHours()
var todaymin=today.getMinutes()
var todaysec=today.getSeconds()
var todaystring=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec
futurestring=montharray[m-1]+" "+d+", "+yr
dd=Date.parse(futurestring)-Date.parse(todaystring)
dday=Math.floor(dd/(60*60*1000*24)*1)
dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1)
dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1)
dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1)
if(dday==0 && dhour==0 && dmin==0 && dsec==0){
$that.val(current);
return
}
else
$that.val("Only "+dday+ " days, "+dhour+" hours, "+dmin+" minutes, and "+dsec+" seconds left "+before);
setTimeout(function(){ $that.countdown(theyear,themonth,theday);},1000)
}
<?php
include('../connection.php');
$rs = mysql_query("select * from datepic") or die(mysql_error());
if(mysql_num_rows($rs)){
while($row = mysql_fetch_array($rs))
{
$date = str_replace('-',',',$row['date']);
echo '<input type="text" id="'.$row['id'].'" size=80>';
?>
<script>
$("?php echo $row['id'] ?>").countdown(<?php echo $date?>);
</script>
<?php
}
}
?>
I have this code so far that redirects the user after 5 seconds to the correct URL:
<?php
$url = $_GET['url'];
header("refresh:5;url=$url");
include('ads.php');
?>
Please could you tell me how i could display a countdown timer saying Redirecting In.. with .. being the amount of seconds left. I am new to web development so all code will be helpful!
<script type="text/javascript">
(function () {
var timeLeft = 5,
cinterval;
var timeDec = function (){
timeLeft--;
document.getElementById('countdown').innerHTML = timeLeft;
if(timeLeft === 0){
clearInterval(cinterval);
}
};
cinterval = setInterval(timeDec, 1000);
})();
</script>
Redirecting in <span id="countdown">5</span>.
You can try this.
As this is a common beginner question; I just wanted to highlight that for best practise setInterval should, and can usually be avoided by using setTimeout recursively within a function.
For example:
var timer = 5,
el = document.getElementById('countdown');
(function t_minus() {
'use strict';
el.innerHTML = timer--;
if (timer >= 0) {
setTimeout(function () {
t_minus();
}, 1000);
} else {
// do stuff, countdown has finished.
}
}());
Excellent code by Kyle. I have modified the timer with a pause and resume button.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var time_left = 50;
var cinterval;
var timestatus=1;
function time_dec(){
time_left--;
document.getElementById('countdown').innerHTML = time_left;
if(time_left == 0){
clearInterval(cinterval);
}
}
function resumetime()
{
//time_left = 50;
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
}
function defaultstart()
{
time_left = 50;
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
}
function stopstarttime()
{
if(timestatus==1)
{
clearInterval(cinterval);
document.getElementById('stopbutton').value="Start";
timestatus=0;
}
else
{
clearInterval(cinterval);
cinterval = setInterval('time_dec()', 1000);
document.getElementById('stopbutton').value="Stop";
timestatus=1;
}
}
defaultstart();
</SCRIPT>
</HEAD>
<body>
Redirecting In <span id="countdown">50</span>.
<INPUT TYPE="button" value="stop" id="stopbutton" onclick="stopstarttime()">
</body>
</HTML>
Here is my take on it, without variables outside of the function. Depends on jQuery.
function count_down_to_action(seconds, do_action, elem_selector)
{
seconds = typeof seconds !== 'undefined' ? seconds : 10;
$(elem_selector).text(seconds)
var interval_id = setInterval(function(){
if (seconds <= 0)
{
clearInterval(interval_id);
if (typeof do_action === 'function')
do_action();
}
else
$(elem_selector).text(--seconds);
},1000)
}
Here is an example using it http://jsfiddle.net/VJT9d/