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
}
}
?>
Related
Consider the following PHP Block. I want to output "name" to div #1 and "slog" to div #2
<?php
require_once 'db_conx.php';
$Result = mysql_query("SELECT * FROM profiles ORDER BY lastupdated desc limit 1") or die (mysql_error());
while($row = mysql_fetch_array($Result)){
$result = array();
$result['name'] = $row['name'];
$result['slog'] = $row['slog'];
echo json_encode($result);
}
mysql_close($con);
?>
Here's the ajax that just outputs json itself.
var get_fb = (function() {
var counter = 0;
var $buzfeed = $('#BuzFeed');
return function(){
$.ajax({
type: "POST",
url: "../php/TopBusinesses_Algoriththm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>").addClass('flat-menu-button');
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.last().remove(); }
setTimeout(get_fb, 1000);
})
};
})();
get_fb();
You can update the html/content of a DOM element with the following:
document.getElementById(name).innerHTML = "text";
So in this instance:
document.getElementById('#1').innerHTML = $yourNameContent;
document.getElementById('#2').innerHTML = $yourSlogContent;
First: move var counter = 0; outside from get_fb() function;
Second: Do not call get_fb(); explicitly, because (function(){...})(); already calls method after initialization.
Third: Why use POST method if there is not data to submit!
So, do this and have a try:
var counter = 0;
var $buzfeed = $('#BuzFeed');
var get_fb = (function() {
$.ajax({
type: "GET",
url: "../php/TopBusinesses_Algoriththm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>").addClass('flat-menu-button');
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.last().remove(); }
setTimeout(get_fb, 1000);
})
})();
I am newbie in php and still learn javascript function.
I have a problem with, include javascript variable into php query.
I want to create transaction code according count of part code which have different type. then i must get value with count.
<script language="javascript" type="text/javascript">
function getCode(){
var v =document.forms["form1"]["part_code"].value;
<?php
$query = mysql_query("SELECT COUNT(*)+1 as count FROM TB_TRANSACTION where part_code = "<script>v;</script>"");
$i=-1;
while ($code_part = mysql_fetch_array($query))
{
$i++;
?>
var getPartCode = <? echo $code_part['count'];?>;
var x = document.forms["form1"]["part_code"].value;
var y = document.forms["form1"]["location_code"].value;
var z = document.forms["form1"]["date"].value;
var a = (getPartCode + '/'+x +'/'+ y +'/'+ z);
document.forms["form1"]["invent_code"].value = a;
<?
}
?>
</script>
The result like that 1/CPU/JKT/2013
I call that function with button onClick="getCode()" no submit.
Anyone can help me.
You can't do it by the way you tried.There are two better ways to do it
Use Ajax.
Use Cookies
The best way here is to use Ajax. Here, iam using javascript and ajax.And i am creating a new file to create response(say newfile.php) Try this,
function getCode(){
var v =document.forms["form1"]["part_code"].value;
var x = document.forms["form1"]["part_code"].value;
var y = document.forms["form1"]["location_code"].value;
var z = document.forms["form1"]["date"].value;
var xmlhttp;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var getPartCode=xmlhttp.responseText; //Getting the response from php file
var a = (getPartCode + '/'+x +'/'+ y +'/'+ z);
document.forms["form1"]["invent_code"].value = a;
}
}
xmlhttp.open("GET","newFile.php?q="+v,true); //Sending request to newfile.php
xmlhttp.send();
}
</script>
newfile.php
<?php
$value = $_GET["q"]; //getting the value sent through tthe ajax request
$query = mysql_query("SELECT COUNT(*)+1 as count FROM TB_TRANSACTION where part_code = '$value'");
$i=-1;
while ($code_part = mysql_fetch_array($query))
{
$i++;
echo $code_part['count'];
}
?>
Best Method is Ajax
Otherwise Use Cookies
For Eg:
<script type="text/javascript">
document.cookie = "cookieName=cookieValue";
</script>
<?php
$phpVar = $_COOKIE['cookieName'];
echo $phpVar;
?>
Your code
<script language="javascript" type="text/javascript">
function getCode(){
var v =document.forms["form1"]["part_code"].value;
document.cookie = "cookieName="+v;
<?php
$phpVar = $_COOKIE['cookieName'];
$query = mysql_query("SELECT COUNT(*)+1 as count FROM TB_TRANSACTION where part_code = '$phpVar'");
$i=-1;
while ($code_part = mysql_fetch_array($query))
{
$i++;
?>
var getPartCode = <? echo $code_part['count'];?>;
var x = document.forms["form1"]["part_code"].value;
var y = document.forms["form1"]["location_code"].value;
var z = document.forms["form1"]["date"].value;
var a = (getPartCode + '/'+x +'/'+ y +'/'+ z);
document.forms["form1"]["invent_code"].value = a;
<?
}
?>
</script>
Updated
Check this
function getCode(){
var v = 12;
document.cookie = "cookieName="+v;
var getPartCode = <?php echo $_COOKIE['cookieName']; ?>
alert(getPartCode);
}
Hey I would to create a live clock to put it on my website. So I wrote a simple php with JavaScript code for that, here is it:
<?php
Function d1() {
$time1 = Time();
$date1 = date("h:i:s A",$time1);
echo $date1;
}
?>
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
document.getElementById('qwe').innerHTML = '<?php d1();?>';
}
</script>
<div id="qwe">test</div>
When run this code the output like "2:40:17 PM", the div refreshed every second but the problem is the time never changed.
Get the initial time you want to start your clock with from PHP:
<script>
var now = new Date(<?php echo time() * 1000 ?>);
function startInterval(){
setInterval('updateTime();', 1000);
}
startInterval();//start it right away
function updateTime(){
var nowMS = now.getTime();
nowMS += 1000;
now.setTime(nowMS);
var clock = document.getElementById('qwe');
if(clock){
clock.innerHTML = now.toTimeString();//adjust to suit
}
}
</script>
For formatting the date there's a zillion options (MDN Date API: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date)
<script type="text/javascript">
function timedMsg()
{
var t=setInterval("change_time();",1000);
}
function change_time()
{
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();
if(curr_hour > 12)
curr_hour = curr_hour - 12;
document.getElementById('Hour').innerHTML =curr_hour+':';
document.getElementById('Minut').innerHTML=curr_min+':';
document.getElementById('Second').innerHTML=curr_sec;
}
timedMsg();
</script>
<table>
<tr>
<td>Current time is :</td>
<td id="Hour" style="color:green;font-size:large;"></td>
<td id="Minut" style="color:green;font-size:x-large;"></td>
<td id="Second" style="color:red;font-size:xx-large;"></td>
<tr>
</table>
use this way to display time........
enjoy the above script
You can use ajax to refresh the time:
Example:
<?php
if(#$_GET["action"]=="getTime"){
$time1 = Time();
$date1 = date("h:i:s A",$time1);
echo $date1; // time output for ajax request
die();
}
?>
<div id="qwe">test</div>
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
AX = new ajaxObject("?action=getTime", showTime)
AX.update(); // start Ajax Request
}
// CallBack
function showTime( data ){
document.getElementById('qwe').innerHTML = data;
}
</script>
<script type="text/javascript">
// Ajax Object - Constructor
function ajaxObject(url, callbackFunction) {
var that=this;
this.updating = false;
this.abort = function() {
if (that.updating) {
that.updating=false;
that.AJAX.abort();
that.AJAX=null;
}
};
this.update =
function(passData,postMethod) {
if (that.updating) { return false; }
that.AJAX = null;
if (window.XMLHttpRequest) {
that.AJAX=new XMLHttpRequest();
}else{
that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (that.AJAX==null) {
return false;
}else{
that.AJAX.onreadystatechange = function() {
if (that.AJAX.readyState==4) {
that.updating=false;
that.callback( that.AJAX.responseText, that.AJAX.status, that.AJAX.responseXML, that.AJAX.getAllResponseHeaders() );
that.AJAX=null;
}
};
that.updating = new Date();
if (/post/i.test(postMethod)) {
var uri=urlCall+(/\?/i.test(urlCall)?'&':'?')+'timestamp='+that.updating.getTime();
that.AJAX.open("POST", uri, true);
that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
that.AJAX.setRequestHeader("Content-Length", passData.length);
that.AJAX.send(passData);
}else{
var uri=urlCall+(/\?/i.test(urlCall)?'&':'?')+passData+'×tamp='+(that.updating.getTime());
that.AJAX.open("GET", uri, true);
that.AJAX.send(null);
}
return true;
}
};
var urlCall = url;
this.callback = callbackFunction || function (){};
}
</script>
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";
<? while($row = mysql_fetch_array($result))
{
$result2 = $row['end_time'];
echo"<td><div id=defaultCountdown></div></td>";
?>
<script type=text/javascript>
$(function ()
{
var t = ('<? echo $result2; ?>').split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
$('#defaultCountdown').countdown({until: d});
$('#year').text(austDay.getFullYear());
});
</script>
<? }
?>
So basically I wanted to launch the Javascript countdown timer for each row of results generated by mysql_fetch_array. However, in the code above, the timer only works for the first row of result. How do I make the timer work for every row of result?
EDIT
<td> 2012-12-17 13:12:22</td><td> <img src = Images/1324133424.jpg height=200 width=300 /> </td><td> active</td><td><div id=defaultCountdown0></div></td>
<script type=text/javascript>
$(function ()
{
var t = ('2012-12-17 13:12:22').split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
$('#defaultCountdown0').countdown({until: d});
$('#year').text(austDay.getFullYear());
});
</script>
<td> 2012-12-01 13:12:22</td><td> <img src = Images/1322754818.jpg height=200 width=300 /> </td><td> active</td> <td><div id=defaultCountdown1></div></td>
<script type=text/javascript>
$(function ()
{
var t = ('2012-12-01 13:12:22').split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
$('#defaultCountdown1').countdown({until: d});
$('#year').text(austDay.getFullYear());
});
</script>
In your PHP while loop, you are setting the same ID for all divs, which is probably why only the first row works. However, as I said in my comment, you need to add the actually JavaScript that is generated by your PHP code.
echo"<td><div id=defaultCountdown></div></td>";
EDIT:
Here's what the code should look like. Run it as it is and then try making small changes to get it to do what you want:
<?
while($row = mysql_fetch_array($result))
{
$i = 0;
$result2 = $row['end_time'];
echo "<td><div id=defaultCountdown$i></div></td>";
?>
<script type=text/javascript>
$(function ()
{
var t = ('<? echo $result2; ?>').split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
$('#defaultCountdown<?php echo $i; ?>').countdown({until: d});
$('#year').text(austDay.getFullYear());
});
</script>
<?
$i++;
}
?>