here i was making a sample program in php.In which i included the java script and used the date but i am getting the same date every time.let have a look on the code.
<?php
?>
<html>
<head>
<title>my app</title>
<script type="text/javascript" src="jquery-2.0.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var time1=new Date();
var time_stack=new Array();
var time;
$(this).mousemove(function(){
time=time1.getSeconds();
alert(time1);
});
});
</script>
</head>
<body>
<h2>we are on the main_session</h2>
</body>
</html>
now the problem is that when i move the mouse than i get an alert box popping out and the date which is being displayed is same all time.Please let me know the problem
Try this
$(document).ready(function(){
$(this).mousemove(function(){
var time1=new Date();
time=time1.getSeconds();
alert(time);
});
});
Hope it will help
Hi, You should assign value for time1 variable in the mousemove() function. Use like this:
$(this).mousemove(function(){
var time1 = new Date();
var time_stack = new Array();
var time;
time = time1.getSeconds();
alert(time1);
});
This is because time1 is evaluated only once when the page loads, on every mouse event you just get the seconds from when it was initialized
The variable time1 never changes, the Date object is the same, so you always get the same time ?
You have to either update the Date on each mousemove, or just get a new Date object :
<html>
<head>
<title>my app</title>
<script type="text/javascript" src="jquery-2.0.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(this).mousemove(function(){
var time1 = new Date();
console.log( time1.getSeconds() );
});
});
</script>
</head>
<body>
<h2>we are on the main_session</h2>
</body>
</html>
FIDDLE
The Date object your instancing isn't a stop watch that will get the current time when you call a method on it. You need to instances a new Date object in your event handler.
alert(new Date().getSeconds());
There is a misprint:
alert(time), not time1 and try this:
$(this).mousemove(function(){
var time1=new Date();
time=time1.getSeconds();
alert(time);
});
Related
Greetings everyone,
I am having a problem in which I need to set the datepicker to be following the semester start date and semester end date such as below.
The most simple way that I know on how to start date and end date in the datepicker is using the code below:
$(document).ready(function(){
$('#appointment_date').datepicker({
format: "yyyy-mm-dd",
daysOfWeekDisabled: [0, 6],
startDate: new Date('2019-1-14'),
endDate: new Date('2019-5-14')
});
});
However, I am supposed to restrict the date by using AJAX and PHP. So I modified the code to be as below:
$('#appointment_date').datepicker({
format: "yyyy-mm-dd",
daysOfWeekDisabled: [0, 6],
$.ajax({
type: 'POST',
url: '../ajax/ajax-get-semester-date.php',
data: {'appointment_date': $('#appointment_date').val()},
success: function (data)
{
$('#appointment_date').append(data);
}
// startDate: new Date('2019-1-14'),
// endDate: new Date('2019-5-16')
});
});
I am not sure what ID should I pass through the data and I am not sure how to append the data for the startDate and endDate. Please help me to solve this problem. Thanks in advance.
You can do this: Datepicker has an option maxDate and minDate
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Restrict date range</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<!-- <link rel="stylesheet" href="/resources/demos/style.css"> -->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<p>Date: <input type="text" id="datepicker"></p>
<script>
$( function() {
$("#datepicker").datepicker({
dateFormat:'yy-mm-dd',
minDate:'2019-04-5',
maxDate:'2019-04-10'
});
});
</script>
</body>
</html>
UPDATE
I finally found an answer to my question. Just sharing here for everyone's knowledge. I referred to an answer here.
In the PHP side, do this:
<?php
//select semester date
$select_date_query = "SELECT semester_end FROM semester ORDER BY semester_end ASC";
$select_date_stmt = $db->prepare($select_date_query);
$select_date_stmt->execute();
if($select_date_stmt)
{
$semDates = array();
while ($row = $select_date_stmt->fetch(PDO::FETCH_ASSOC))
{
$semDates[] = $row['semester_end'];
}
$maxDate = explode("-", end($semDates));
$maxDate[1] -= 1;
}
?>
The datepicker that I used previously is of the Bootstrap datepicker. I forgot to remove the datepicker.js previously which explains why the answer provided by Rasa Mohamed and vwadhwa3 is not working. Thanks you guys for willing to answer even though its not really what I wanted.
In the JQuery datepicker side, do this:
<script>
$(document).ready(function(){
$('#appointment_date').datepicker({
dateFormat:'yy-mm-dd',
beforeShowDay: $.datepicker.noWeekends,
minDate: 0,
maxDate: new Date(<?php echo($maxDate[0]);?>,<?php echo($maxDate[1]);?>,<?php echo($maxDate[2]); ?>)
});
});
</script>
In this i am posting a question in which i am using a java script and PHP code and sending back the timestamp using the time function of the PHP. let have the code,
<?php
session_start();
echo time();
?>
<html>
<head>
<title>my app</title>
<script type="text/javascript" src="jquery-2.0.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(this).mousemove(function(){
var time_=new Date();
var time=<?php echo time();?>;
alert(time);
$.post('loggout.php',{input: time});
});
});
</script>
</head>
<body>
<h2>we are on the main_session</h2>
</body>
</html>
now the problem is that when i move the mouse than the mousemove event gets into action and displays the value of the var time. but every time it displays the same value. the value only changes when i reload the page. so please let me know the reason behind it and how to make this dynamic
This is because the PHP is only run once - when the page loads. So the Javascript time variable gets filled with the time returned by PHP and then never changes.
If you're happy to get the client-side time, just use this:
var time = time.getTime();
Instead of var time=<?php echo time();?>;
Otherwise, you can use AJAX to send a query that'll run some PHP, return the time, and put it into the variable.
For example, you could try something like this:
$.get('getTime.php', function(data) {
time = data;
});
And in getTime.php, just echo the time.
This is because PHP is back-end programing language and once your page loaded timestamp written to code and can't be dynamic. But you can send JS timestamp:
var time = Math.round(+new Date() / 1000);
( + will convert date Object to integer )
or
var time = Math.round(new Date().getTime() / 1000);
division by 1000 needed because JS use milliseconds.
See Date reference at MDN.
put this javascript code anywhere in your php file.
<script type="text/javascript">
var currenttime = '<?php echo date("F d, Y H:i:s"); ?>' //PHP method of getting server date
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
var serverdate=new Date(currenttime)
function padlength(what){
var output=(what.toString().length==1)? "0"+what : what
return output
}
function displaytime(){
serverdate.setSeconds(serverdate.getSeconds()+1)
var datestring=montharray[serverdate.getMonth()]+" "+padlength(serverdate.getDate())+", "+serverdate.getFullYear()
var timestring=padlength(serverdate.getHours())+":"+padlength(serverdate.getMinutes())+":"+padlength(serverdate.getSeconds())
document.getElementById("servertime").innerHTML=timestring
}
window.onload=function(){
setInterval("displaytime()", 1000);
}
</script>
add span or div where you want to show current time. no need to reload page.
<span id="servertime"></span>
My code
$sql="SELECT * FROM `room_lists`";
$sqlquery = mysql_query($sql);
while($result = mysql_fetch_array($sqlquery)){
$toDay = strtotime($result['timeStop']);
//echo $toDay;
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=tis620" />
<script type="text/javascript" src="core/jquery-latest.js"></script>
<title>test</title>
<script type="text/javascript">
function countDown(times){
var toDay=Math.round(new Date().getTime()/1000);
var difTime=times-toDay;
var day=0,hours=0,minutes=0,seconds=0;
if(difTime>0){
day=Math.floor(difTime/84600);
hours=Math.floor((difTime/3600))%24;
minutes=Math.floor(difTime/60)%60;
seconds=Math.floor(difTime)%60;
countDown_onLoad();
}
else{
alert('asd'); //time out
}
$('.show').html(day+' Day '+hours+' Hour '+minutes+' Min '+seconds+' Sec ');
}
function countDown_onLoad(){
setTimeout("countDown(<?=$toDay ?>);",1000);
}
$(document).ready(function() {
countDown_onLoad();
});
</script>
</head>
<body>
<div class="show"></div>
</body>
</html>
<? } ?>
Hello, I am a newbie using javascript. I have created countdown timer to use like auction website with js function that call from database(timestamp type) with php query, if the result is 1 row, it works fine but if more than 1 the result are all the same as last row in database. How can I fix this?
This is my output
0 Day 1 Hour 41 Min 25 Sec
0 Day 1 Hour 41 Min 25 Sec
You appear to be outputting an entire HTML document (less the opening <html> tag and <!doctype>) for every counter.
The core problem is that you are using $(".show").html(...) to output the counter, which is essentially telling it to put that content in every .show element. The net result is that they all show the same thing: whatever the last counter is at.
Your approach is almost unsalvageable, but here is my best attempt:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=tis620" />
<script type="text/javascript" src="core/jquery-latest.js"></script>
<title>test</title>
<script type="text/javascript">
function countDown(){
var toDay=Math.round(new Date().getTime()/1000);
$(".show").each(function() {
var elm = $(this);
var difTime=this.timestamp-toDay;
var day=0,hours=0,minutes=0,seconds=0;
if(difTime>0){
day=Math.floor(difTime/84600);
hours=Math.floor((difTime/3600))%24;
minutes=Math.floor(difTime/60)%60;
seconds=Math.floor(difTime)%60;
}
else{
alert('asd'); //time out
elm.removeClass("show");
}
elm.html(day+' Day '+hours+' Hour '+minutes+' Min '+seconds+' Sec ');
});
}
function countDown_onLoad(){
$(".show").each(function() {
this.timestamp = parseInt(this.firstChild.nodeValue,10);
});
setInterval(countDown,1000);
}
$(document).ready(function() {
countDown_onLoad();
});
</script>
</head>
<body>
<?php
$sql="SELECT * FROM `room_lists`";
$sqlquery = mysql_query($sql);
while($result = mysql_fetch_array($sqlquery)){
$toDay = strtotime($result['timeStop']);
echo "<div class=\"show\">".$toDay."</div>";
}
?>
</body>
</html>
Please note that I do not use jQuery. I am only using it here because you were already using it. With that in mind I may have incorrectly used .each(). Please let me know if you encounter any errors and I will try to fix them.
if you are displaying countdown then there must be one time, not multiple, so first set LIMIT 1 when you retrieve the value
instead of doing this
function countDown(times){
// blah blah blah
}
function countDown_onLoad(){
setTimeout("countDown(<?=$toDay ?>);",1000);
}
$(document).ready(function() {
countDown_onLoad();
});
try with below approach
var countdown = function(myTime)
{
// blah blah blah
}
window.setInterval(countdown(<?=$toDay?>), 1000);
I want to show the time which I have in my php variable with the help of Javascript
I am coding an online exam module, where I want to display the total elapsed time
say for example
$time_elapsed // contains the time taken till now from the start of the exam
And if I got a div say,
<div id="time"></div>
how can I show the dynamic running time with starting from $time_elapsed after load the window for each question
Please if you guys have an answer for this..
Thanks
hi you can use the following code for the purpose
the javascript will be:
var Timer;
var TotalSeconds,TotalMins, secs;
var elapsedtime ;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
elapsedtime = 0
time = Time
secs = TotalSeconds%60;
TotalMins = Math.floor(TotalSeconds/60)
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if(TotalSeconds-elapsedtime>0)
{
elapsedtime += 1;
secs = (elapsedtime%60)-60;
TotalMins = Math.floor(elapsedtime/60)
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
else
alert("time up")
}
function UpdateTimer() {
Timer.innerHTML = TotalMins + ":" + secs;
}
nw create a html div where you want to show the running time.
Html:
<div id='timer' />
<script type="text/javascript">window.onload = CreateTimer("timer", 5);</script>
give parameter the time limit. it will alert after time finishes.
and to get time after refresh of the page use html5's sessionStorage
visit Html5 Storage Doc to get more details. using this you can store intermediate values temporaryly/permanently locally and then access your values
for storing values for a session
sessionStorage.getItem('label')
sessionStorage.setItem('value', 'label')
or store values permanently using
localStorage.getItem('label')
localStorage.setItem('value', 'label')
So you can store (temporarily) form data between multiple pages using html5 storage objects
This is how to display dynamic time. To use other php based starting time replace the line time0 = new Date(); by time0 =<?php echo $startTime;?>; which should be in ms since the epoch.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>elapsed time demo</title>
<script type="text/javascript">
var time0;
function initTime() {
time0 = new Date();
window.setInterval("updateTime()", 1000);
}
function updateTime() {
var timeNow = new Date();
var deltas = (Number(timeNow) - Number(time0))/1000;
var deltah = ("0"+String(Math.round(deltas / 3600))).substr(-2);
deltah = deltah.substr(-2);
deltas %= 3600;
var deltam = ("0"+String(Math.round(deltas / 60))).substr(-2);
deltas = ("0"+String(Math.round(deltas % 60))).substr(-2);
document.getElementById("timedisplay").firstChild.data=deltah+":"+deltam+":"+deltas;
}
</script>
</head>
<body onload="initTime();">
<div> elapsed time <span id="timedisplay">00:00:00</span></div>
</body>
</html>
Your php code should return the time elapsed at the point of loading the page, however, javascript will then take over and increment that time as time passes.
You can send the parameter to your JavaScript function which is display time
function display_time(int time)
{
//your code for further integration
}
You can send the parameter to JavaScript function using following way
//call the function at the time display time
display_time(<?php echo $time_elapsed ?>)
I have the following code. How to convert lonlat value to GPS used values in degrees?
UPDATE: I'm not sure that I use correct vocabulary, but currently lonlat is equal to something like this '2698.98978 1232.8998'. I want to conver to degrees, e.g. '41.2987 2.1989'.
lonlat is a variable. Please see in the code.
<html>
<head>
<script src="http://openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
function init(){
map = new OpenLayers.Map('map');
base_layer = new OpenLayers.Layer.WMS( "OpenLayers WMS",
"http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} );
map.addLayer(base_layer);
map.zoomToMaxExtent();
map.events.register('click', map, handleMapClick);
}
function handleMapClick(evt)
{
var lonlat = map.getLonLatFromViewPortPx(evt.xy);
// use lonlat
alert(lonlat);
}
</script>
</head>
<body onload="init()">
Hello Map.<br />
<div id="map"></div>
</body>
</html>
You shouldn't use the getLonLatFromViewPortPx but the getLonLatFromPixel method like this:
var lonlat = map.getLonLatFromPixel(evt.xy);
This will give you the correct coordinates without any transforms.