Is there any way to get the current time of website in order to set range time for reaction?
e.g if current time of website >= 14:00 && current time of website < 15:00
do reaction
else
another reaction
I want to do this checking type of fuction every 30' sec
EDITED
e.g If in my country the time is 14:00 and in another one is 19:00 I want to do the reaction to another country based in my country's time. Correct my if I do smthng wrong.
here is the code for php file to fetch server time, name it t.php.
<?php
$b = time ();
echo date("H",$b);
?>
and here is the code for other file on which you use ajax: Run this file using xamp/wamp.
Place both files in sane directory .
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
setInterval(function() {
$.ajax({
url : "t.php",
type: 'GET',
success: function(data){
if(data >= 9 && data < 10){
alert('yes');
// do something
} else{
alert('no');
// do something
}
}
});
}, 1000);
</script>
Here is the Solution:
you can find current time of website using javascript because it is a client side scripting language
In php I think there is no way to find client's time (not sure), That's why I am using jquery.
to use it in php file use ajax.
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
function call_notification_count() {
var todaydate = new Date(); // current time of browser. or you can say Time of client's location
var month = todaydate.getMonth()+1+"";if(month.length==1) month="0" +month;
var date = todaydate.getDate()+"";if(date.length==1) date="0" +date;
var year = todaydate.getFullYear();
var hours = todaydate.getHours();
var minutes = todaydate.getMinutes();
var seconds = todaydate.getSeconds();
var todaytime = hours+":"+minutes+":"+seconds;
var todaydateonly = year+"-"+month+"-"+date+" ";
alert(todaytime);
if(hours >= 14){
// do something
}else{
// do something
}
}
setInterval(call_notification_count, 3000); // Set time intervel here like for every 30 sec.
});
</script>
Related
I am trying to make a program which counts down over the space of 15 seconds and displays them using PHP and JQuery. I need to be able to automatically load the server's timestamp into the strtotime function and set this to the start point of the timer, and make the end point of the timer 15 seconds after this point, is there any way I can achieve this?
I have tried setting the times specifically and the timer works for counting to 15 seconds after these points, but I need it to set these times relative to the current moment automatically, as I want it to start and stop the timer at certain undecided points in the program as it is running. I have also tried the reference values 'now' and '-15 seconds' - but these seem to stop the timer at '15 seconds remaining' and it does not count down from this point.
timer.php:
<?php
if(true) {
$countdownEnd = strtotime("-15 seconds");
$countdownStart = strtotime("now");
$timeLeft = $countdownEnd - $countdownStart;
if(isset($_POST["type"]) === true && $_POST["type"] == "timerupdate") {
echo ($timeLeft);
}
}
?>
timer.js:
$(function() {
var timerText = $("[timer]");
setInterval(function() {
$.post("timer.php", {type : "timerupdate"}, function(data){
timerText.html(data + " seconds remaining")
});
}, 1000);
});
timer tests.php:
<!DOCTYPE HTML>
<html>
<head>
<script type="application/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="application/javascript" src="timer.js"></script>
</head>
<body>
<?php include("timer.php") ?>
<p timer></p>
</body>
</html>
I expect the output to be a timer which counts down from 15 seconds whenever the starting condition (the if statement at the beginning of timer.php) becomes true.
Any help is really appreciated, thanks :)
If you want to save the timer after reload you need something like a session with a cookie. have a look at https://php.net/manual/en/function.session-start.php
//start a session and make sure there is no output before
session_start();
//maybe you want to check for the requestmethod before you do additional checks
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//your check for timerupdate.
//you dont have to exact bool compare to true the isset it can only return true or false.
if (isset($_POST["type"]) && $_POST["type"] == "timerupdate") {
if (!isset($_SESSION['time'])) $timeLeft = 15;
else $timeLeft = 15 - (time() - $_SESSION['time']);
//output the timer or whatever you want
if ($timeLeft < 0) echo 0;
else echo $timeLeft;
}
}
you have to add settings: withCredentials: true into your ajax call in order to send cookies
Can you check with using date function with time .
<?php
$time=time();
$time_out=$time-60*24;
if($userInfo['deleteTime'] < $time_out){
?>
<td><small class="showExpire">Timeout..You Cannot Reverse the Deleted Request</small></td>
<?php } else { ?>
<td><small>Cancel Deleting Request</small></td>
<?php }?>
this is static script and want to make compatible with my code
<script language="JavaScript">
TargetDate = "12/27/2017 10:56 PM";
BackColor = "palegreen";
ForeColor = "navy";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
FinishMessage = "It is finally here!";
</script>
when user delete something then
I gave him 24 hrs to reverse his delete and before 24hrs get completed then i have shown cancel Delete button and if 24 hrs are done from the time he deleted then he will not be able to reverse the delete and has shown Timeout message. But now i m not able to put 24 hour countdown for that user when he will delete then he should know that he left x time to reverse his delete
how do i use countdown for this logic
You can achieve this using jquery,ajax and php as
<script>
setInterval(countDownTimer, 1000); // call your function at regular interval of time
function countDownTimer()
{
$.ajax({
url : 'your php file path',
method : 'get',
success : function(response)
{
if(response.errCode == 0)
{
$('your table id').append("<td><small class="showExpire">Timeout..You Cannot Reverse the Deleted Request</small></td>")
} else
{
$('your table id').append("<td><small>Cancel Deleting Request</small></td>");
}
},
})
}
</script>
// in php file
<?php
$time=time();
$time_out=$time-60*24;
if($userInfo['deleteTime'] < $time_out){
return response()->json(['reqId'=>'your id']);
} else {
return response()->json(['errCode'=>0]);
}
My code is as follows -
<div class="huge">
<?php echo date ("g:i:s A"); ?>
</div>
How do i set <div class="huge"> to refresh every second?
Assuming that you need to get the update from the server (noted the PHP code in your original post), there are two things you need to implement:
A Server-Side script (in this case written in PHP) to be requested by the client for fresh data.
A Client-Side javascript to fetch fresh data from the server and update your div.
Let's make an example.
index.php
<html>
<head>
<title>My date updater</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
<div class="huge"><?php echo date ("g:i:s A"); ?></div>
</body>
</html>
Javascript (using jQuery)
setInterval(function(){
$.ajax({
url:'loadData.php'
}).done(
function(data){
$('.huge').html(data);
});
},1000);
loadData.php
<?php echo date ("g:i:s A"); ?>
Initially your page named in this example index.php will load and show the initial date (using a bit of php code inline).
Then the javascript will start to get data from the server (using an ajax request to loadData.php) every second and the div will be updated with the fresh data.
Hope it helps a bit!
P.S: Date and time information can also be fetched using pure javascript code on the client-side, but for some applications the date and time information on the client-side is not reliable enough since it relies on the date and time settings that are set by the client browser.
You could use Ajax, something like this:
If it's just simple text, or simple HTML being loaded then you could use
setInterval(function(){
$("#huge").load("now_playing.php");
...
}, 5000);
You could also use something like:
function reload() {
jQuery.ajax({
url: "fetch_message.php",
type: "POST",
success:function(data){
$('#huge').innerHTML(data);
setTimeout(function(){
reload()
}, 1000);
}
});
This will update the content of the element with id="huge" every second. you don't need any initial php value.
If you need other elements like minutes and seconds of course you can add dt.getMinutes() and dt.getHours() to the string.
<div id="huge"></div>
<script language="javascript">
function refreshSomething(){
var dt = new Date();
document.getElementById('huge').innerHTML = dt.getSeconds();
}
setInterval(function(){
refreshSomething() // this will run after every second
}, 1000);
</script>
This works too -
<script>function getTime(){
var date = new Date();
date.setTime(Date.now());
return (date.getHours() % 12) + ':' + leadingzero(date.getMinutes()) + ':' + leadingzero(date.getSeconds()) + (date.getHours() < 12 ? ' AM' : ' PM'); ;
}
function leadingzero(n) {
return (n < 10) ? ("0" + n) : n;
}
function updateDiv(){
var d = document.document.getElementsByClassName('yourDivClassname')[0];
d.innerHTML = getTime();
}
setInterval(updateDiv, 1000);</script>
Html5 login localstorage for days. This HTML5 Login script uses localstorage to stores users that and everything works fine.
But I need to add one more thing. I want once the user log in for the first time, the app will store the users info in html5
browser for like 30 days, when 30 days elapse, the user will be redirected back to login again. Can someone help me with that?
Thanks.
<script>
$(document).ready(function(){
$('.send').click(function(){
var uname=$('#uname').val();
var pass=$('#pass').val();
if(uname==""){
$('.error').effect("bounce",500).fadeIn(400).html('Enter Your Username');
}
else if(pass==""){
$('.error').effect("bounce",500).fadeIn(400).html('Enter your password');
}
else{
$('.error').hide();
var userdata= "uname="+uname+"&pass="+pass;
window.localStorage["uname"] = uname;
window.localStorage["pass"] = pass;
$("#loader").show();
$("#loader").fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Checking your details</span>');
$.ajax({
type:"post",
data:userdata,
url:"http://localhost/login.php",
cache:false,
success:function(msg){
$("#loader").hide();
$('.error').fadeIn(200).html(msg);
}
});
}
});
});
</script>
1) localstorage data won't expire like cookie. it will stay like it for years.
2) if you want to set expiration date add expiration date as value to localstorage then retrieve this info every time and check you condition like number of days, or hours, or months.
or
3) use cookie where you can set expiration date.
Simply set when the data is set in the localStorage (via another variable in it), and each time the app loads, check for that value and compare it with the current date/time.
As I mentioned in a comment (and Shomz mentioned in his answer), you need to set the current date in the local storage just as you store the username and password (are you sure you need to store the password in local storage -- doesn't seem necessary) and then check if that value is set and compare it to the current date.
Update: fixing the code (forgot to convert the local storage date from a string back to a date object, plus I had a missing close bracket, oops!).
jsfiddle with an example usage: http://jsfiddle.net/uqpywLv3/17/
<script>
$(document).ready(function(){
$('.send').click(function(){
var uname=$('#uname').val();
var pass=$('#pass').val();
if(uname==""){
$('.error').effect("bounce",500).fadeIn(400).html('Enter Your Username');
}
else if(pass==""){
$('.error').effect("bounce",500).fadeIn(400).html('Enter your password');
}
else{
$('.error').hide();
var userdata= "uname="+uname+"&pass="+pass;
window.localStorage["uname"] = uname;
window.localStorage["pass"] = pass;
// is storing the password this necessary?
$("#loader").show();
$("#loader").fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Checking your details</span>');
$.ajax({
type:"post",
data:userdata,
url:"http://localhost/login.php",
cache:false,
success:function(msg){
// store the current date
window.localStorage["ldate"] = new Date();
$("#loader").hide();
$('.error').fadeIn(200).html(msg);
}
});
}
}); // end .send click handler
// check if the user is logged in
if (typeof window.localStorage["ldate"] != "undefined") {
// localstorage seems to store the date as a string
// so convert it to a date object
var memDate = new Date(window.localStorage["ldate"]);
var expDate = new Date(); // current date.
expDate.setDate(-30); // set to 30 days ago.
if (memDate > expDate) {
// user's last login still valid
// do whatever you think is appropriate here
} else {
// user's last login was past 30 days ago
// perhaps call function to log them out on server side
// and show login form?
}
} else {
// the user is not logged in.
// put your code for showing the login form here
}
});
</script>
I have the follwing code :
<script type="text/javascript">
function myfuncc () {
if (document.cookie.indexOf("visited") >= 0) {
// They've been here before.
alert("hello again");
}
else {
// set a new cookie
expiry = new Date();
expiry.setTime(date.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "visited=yes; expires=" + expiry.toGMTString();
alert("this is your first time");
}
}
</script>
<script type="text/javascript">
window.onload = myfuncc;
</script>
As you can see the window.onload function, I am trying to check if a vistor had already been at the site once the page loads. I am using cookies to do so. Problem is, I can't see the messages I am supposed to. Anyone knows why?
You have to set the expire date using toUTCString() method.
You also have a date object that is not initialized, try this:
function myfuncc () {
if (document.cookie.indexOf("visited") >= 0) {
// They've been here before.
alert("hello again");
}
else {
var expiry = new Date();
expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes
document.cookie = "visited=yes; expires=" + expiry.toUTCString();
alert("this is your first time");
}
}
give this a try:
var testarr = ["knirpsel", "text", "visited=yes"].indexOf("visited");
alert ( testarr );
output is "-1" which means the string "visited=yes" won't be found by search term "visited"
http://jsfiddle.net/m5x3M/
and
What is the best way to get a cookie by name in JavaScript?