I´m a totally newbie in Javascript.
I´m using Wordpress and need a Button that is getting clickable after a predefined time - Like 2 Hours after Posts.
Here´s what i already have.
echo $post_time = $proposal->comment_date;
$t_time = get_the_time( __( 'Y/m/d g:i:s A' ) );
echo "<h1>BLOG TIME</h1>";
echo $t_time . "<br>";
echo $current_time = date("Y-m-d g:i:s A");
$time_to_wait = 60 //Minutes
if ( $post_time < $current_time )
{
echo "ok";
} else { echo "not ok"; }
How to integrate the $time_to_wait Variable?
How should the JavaScript look like?
How to integrate the $time_to_wait Variable?
$post_time and $current_time should be timestamps. $time_to_wait should be milliseconds (60 * 60 * 1000)
Maybe like that: if ($current_time - $time_to_wait > $post_time) { echo '0'; } else { echo '1'; }
(if i understood your question correctly)
How should the JavaScript look like?
Please, describe what do you want? I think it should be like
echo '<button id="your_button" ' . (($current_time - $time_to_wait > $post_time) ? 'disabled="true"' : ''). '">' in your php code.
If you want button to be enabled if time has passed. No JS required. Did i answered your question correctly? If not, please response.
(Excuse me for my grammar)
Related
Recently, ive started tyring out arshaw's fullcalendar. Along the developing journey, i was searching through websites on solution to get the event color to change based on the dates of the event and the current date. This code is written with HTML and PHP with Javascript.
This is an answer to my own questions posts based on what i achieve as there is no similar questions with solutions to this.
So below is my answer and how the FullCalendar looks like.
To clarify, i am using odbc with microsoft Access as database.
My way of doing this is as below:
Events at fullcalendar script
events: [
<?php
include 'connect.php'; //connect to database
function getColor($date) {
$currentDate = date('Y-m-d');
$oneweekDate = date('Y-m-d',strtotime('-1 week')); // this part is to compare with the date 1 week ago
$eventColor = '';
if ($date == $currentDate) {
$eventColor = '#fb8c00';
} else if($date > $oneweekDate && $date < $currentDate){
$eventColor = '#ff0000';
} else if($date < $oneweekDate){
$eventColor = '#696969';
} else {
$eventColor = '#008000';
}
return $eventColor;
}
$sql="SELECT * FROM masterlist1";
$result=odbc_exec($conn,$sql);
while($row=odbc_fetch_array($result)){
$newEnd = date("Y-m-d", strtotime($row['Calibration_Due_Date']));
$color = getColor($newEnd); //store the date from database into a PHP variable and then call the PHP function getColor to get return result
?>
{
title: '--title--', <!--u may get info from fullcalendar.io on the documentations for these parts-->
start: '--start date--',
end: '--end date--',
description : '--description--',
color : '<?php echo $color?>' <!-- this part is where we get the return result from the getColor function and store it into $color variable and then echo it out here for the event color.-->
},
<?php } ?>
],
i am working on my first own website. i try to display which cinema seats are already booked, by turning theire backgroundcolor red. i store the reservations in an sql database. i do get the correct value and i can display it on my website, but still the getById won t work.
This is how i create the divs i want to tune:
<?php
for ($i=0; $i < $saalinfo[2]; $i++) {
echo "<div class='rowsaal'>";
for ($j=0; $j < $saalinfo[3]; $j++) {
$k = $i+1;
echo "<a onclick='JavaScript:removeday($k$j)';>";
echo "<div id='$k$j' class='seat' >";
echo "</div>";
echo "</a>";
}
echo "</div>";
}
?>
This is the way i try to change the background color. I used the exact same js wording in other occasions and it did work so i am guessing my id value is not right:
function getres(){
var date = document.getElementById('labeldate').value;
document.getElementById('showdate').innerHTML = date;
var booked;
booked = "<?php echo $dis; ?>"; //$dis is one value i get back from mysqli_fetch_array in this case its 34
document.getElementById(booked).backgroundColor = "red";
document.getElementById('showdate').innerHTML = document.getElementById('showdate').innerHTML + booked;
}
For clarification: booked shows the correct value which is 34 in this case. In the database itself its saved as a txt value. if i look into the html source code i can see that the value 34 is assigned for booked.
booked = "34";
but the div id is set in the following pattern as it is limitted in the use of '' because they are formed in php
</a><a onclick='JavaScript:removeday(34)';><div id='34' class='seat' ></div></a>
i already had some issues where the use of "" and '' lead to different results. Is this the same case here? and how can i fix the issue? Many thanks in advance.
I have not checked all of your code but there is no "backgroundColor" on the element. You need the style property.
document.getElementById(booked).backgroundColor = "red";
should be
document.getElementById(booked).style.backgroundColor = "red";
I am using a pure JavaScript count down timer that I shared below to redirect to a URL after some time and show the left time to visitor also.
DEMO: JSFiddle
<form name="redirect" id="redirect">
You Will Be Redirected To Next Page After <input size="1" name="redirect2" id="counter"></input>Seconds.
</form>
<script type="text/javascript">
var countdownfrom=5
var currentsecond=document.redirect.redirect2.value=countdownfrom+1
function countredirect(){
if (currentsecond!=0){
currentsecond-=1
document.redirect.redirect2.value=currentsecond
}
else{
showIt()
return
}
setTimeout("countredirect()",1000)
}
countredirect()
function showIt() {
window.location.href = "http://jsfiddle.net/";
}
</script>
Now I want the same function and features and work in pure PHP as you know that many old mobile browsers still does't not support JavaScript and many are using JavaScript blocker. So Is this possible to do the same in Pure PHP, no <script> tags.
UPDATE:
I know the below codes but I want a count down timer too to show to the visitor.
<?php header('Refresh: 5; URL=http://jsfiddle.net/'); ?>
<meta http-equiv="refresh" content="5;url=http://jsfiddle.net/">
Answer:
This can't be done only with php you will need to use jquery or javascript with it. PHP is a server side scripting language you have to use client side language for this task.
Tip:
For redirecting purpose Just use header() function in php to redirect the php file in some time.Your code should look like this
<?php
header( "refresh:5;url=http://jsfiddle.net" );
?>
Hope this helps you...
Well if you want some output, you can't use header(). Alternatively, you could do something like this:
echo "<pre>";
echo "Loading ...";
ob_flush();
flush();
$x = 0;
while($x <= 4) {
$x++;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh" content="0;url=http://jsfiddle.net/">';
PHP is a server-side language. You cannot control how the browser behaves from PHP without some quite complex setup. And even that, you cannot guarantee the behaviour of showing a countdown without JavaScript. For browsers who restrict JavaScript execution, the Refresh header will work just fine. However, for those having JavaScript enabled (which is the majority of browsers nowadays, desktop and mobile alike), a simple header will not give any UI feedback and is frustrating for users who expect responsive applications and web pages.
For this reason, JavaScript can be added, if available, to enhance the automatic, delayed, redirection and give the user some feedback of what's going on. Those with JavaScript disabled will just see a static page, telling them that the page will be redirected, and how long they have to wait for it.
PHP
<?php
$redirectTimeout = 5; // seconds
header('Refresh:' . $redirectTimeout . ';url=http://jsfiddle.net');
// ...
// inside your <head>, add this
echo '<meta http-equiv="refresh" ' .
'content="' . $redirectTimeout . ';url=http://jsfiddle.net">';
// ...
// inside your <body>, add this (or something similar)
echo '<div>' .
'You will be redirected to next page after ' .
'<span id="redirectCountdownLabel">' .
$redirectTimeout .
'</span> seconds' .
'</div>';
// ...
// add JS below
JavaScript
For this part, I recommend you use jQuery. It will not only write safer and cross-browser JS, it will also make your code smaller and prettier. This part can be put anywhere in your HTML, or inside a .js file that you add with a <script> tag. For convenience, you can even add jQuery using a CDN.
!function() {
$(function () {
var meta = $('head meta[http-equiv="refresh"]');
var label = $('#redirectCountdownLabel');
var loadTime;
var refreshTimeout;
if (meta.length && label.length) {
loadTime = window.performance.timing.domComplete;
refreshTimeout = parseInt(meta.attr('content'), 10); // seconds
new Timer(refreshTimeout * 1000, loadTime).start(200, function (elapsed) {
// "elapsed" ms / 1000 = sec
label.text(refreshTimeout - parseInt(elapsed / 1000));
});
}
});
function Timer(maxTime, startTime) {
var timeout;
var callback;
startTime = startTime || Date.now();
function nextTimer(delay) {
timeout = setTimeout(function () {
var curTime = Date.now();
var elapsedTime = curTime - startTime;
callback(elapsedTime);
if (elapsedTime < maxTime) {
nextTimer(delay);
}
}, delay);
}
this.start = function start(ms, cb) {
stop();
callback = cb;
nextTimer(ms);
};
this.stop = function stop() {
if (timeout) {
clearTimeout(timeout);
}
};
};
}();
(Note: here's a jsfiddle of the Timer class.)
scusate per prima, ho postato male, sono ali inizi, sorry
<?php
echo "<pre>";
echo "Loading ...";
ob_flush();
flush();
$x = 21;
while($x >= 1) {
$x--;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh" content="0;url=http://jsfiddle.net/">';
To do the countdown, so it seems to work or am I wrong?
<?php
echo "Loading ...";
ob_flush();
flush();
$x = 21;
while($x >= 1) {
$x--;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh"content="0;url=http://jsfiddle.net/">';
?>`
basically im trying to get equivalent of php time() in javascript
here is the code :
var jstamp = Math.round(new Date().getTime() / 1000) ;
var pstamp = <?php echo time(); ?>;
console.log( 'jstamp is : '+ jstamp);
console.log( 'pstamp is : '+ pstamp);
here is the result :
jstamp is : 13939 45587
pstamp is : 13939 33954
they are way different in the last 5 digits
echo date_default_timezone_get();
echo date('Y-m-d H:i:s');
result :
UTC2014-03-04 11:57:13
server time seems to be wrong , but shouldn't be wrong for both php and js ? meaning that still shouldn't i get the same result in both of them ?
It will probably be the timezone of your server. You can manually set it in PHP: http://php.net/manual/de/function.date-default-timezone-set.php
I have a main select list of courses which drives various things on a page. When a course is selected another select list will be repopulated with the start date of that course up to 6 months in advance. Also, I have a table on the page with the students name and phone number, when a course is selected, the table will be repopulated with all the students enrolled onto that course. My problem is I will be getting various different things from PHP via JSON i.e. the students and the starting date. How can I therefore pass more than one thing to jQuery? What if the course select list affected not just 2 things but 3, 5 or even 10? How would we handle that with PHP and jQuery?
foreach($m as $meta)
{
$metaCourse = $this->getCourseInfo($meta['parent_course']);
//populate the select list with the name of each course
$metaSelectList .= '<option id="select'.$count.'" value="'.$metaCourse['id'].'">'.$metaCourse['fullname'].'</option>';
$count++;
//get only the first course's dates
if($count3 == 1)
{
$startDate = intval( $course->getStartDate(50) );
$endDate = strtotime('+6 month', $startDate);
//populates the select list with the starting date of the course up to the next six months
for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
{
$dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
$count2++;
}
$count3++;
$students = $s->getStudents($metaCourse['id']);
$content = $this->createStudentTable($students);
}
}
This is my handler for the AJAX...FOR NOW (I haven't implemented the students table yet as I'm still trying to figure out how to pass multiple pieces of data to jQuery). Basically each time a course is selected, PHP creates a new select list with the appropriate dates and then passes it to jQuery. I'm not sure if I should do this in JavaScript or in PHP.
if (isset($_GET['pid']) && (isset($_GET['ajax']) && $_GET['ajax'] == "true"))//this is for lesson select list
{
$pid = intval( $_GET['pid'] );
$c = new CourseCreator();
$startDate = intval( $c->getStartDate($pid) );
$endDate = strtotime('+6 month', $startDate);
$dateSelectList = '<select name="dateSelect" id="dateSelect">';
//populates the select list with the starting date of the course up to the next six months
for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
{
$dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
$count2++;
}
$dateSelectList .= '</select>';
echo json_encode($dateSelectList);
exit;
}
My jQuery handler:
$('#metaSelect').live('change', function()
{
$.getJSON('?ajax=true&pid='+$('#metaSelect').val(), function(data)
{
alert(data);
$('#dateSelectDiv').html(data);
});
});
You can easily pass ALOT of data from PHP to your HTML via JSON (which you seem to of put in basic already)
However to expand on what you have - heres a quick example
<?php
$arrayOfStuff = array("theKey" => "theEntry", 123 => "Bob Dow", 56 => "Charlie Bronw", 20 => 'Monkey!', "theMyID" => $_POST['myID']);
echo json_encode($arrayOfStuff);
?>
On your HTML side.
<script>
$.post("/theurl/", {type: "fetchArrayOfStuff", myID: 24}, function(success) {
//your success object will look like this
/*
{
theKey: 'theEntry',
123: 'Bob Dow',
56: 'Charlie Bronw',
20: 'Monkey!',
theMyID: 24
}
so you can easily access any of the data.
alert(success.theKey);
alert(success[123]);
alert(success[56]);
alert(success[20]);
alert(success.theMyID);
*/
//we can iterate through the success JSON!
for(var x in success) {
alert(x + "::" + success[x]);
};
}, "json");
</script>
In the long run - your MUCH better of letting the backend do the backend stuff, and the front end doing the front-end stuff.
What this means is, try keep the HTML generation as far away as possible from the back-end, so instead of constantly passing
for($date = $startDate; $date <= $endDate ; $date = strtotime('+1 day', $date))
{
$dateSelectList .= '<option id="select'.$count2.'" value="'.$date.'">'.date('D d F Y', $date).'</option>';
$count2++;
}
You could perhaps
$date = $startDate;
$myJson = array()
while($date <= $endDate) {
$myJson[] = array("date" => $date, "formattedDate" => date('D d F Y', $date));
$date += 86400; //86400 is the value of 1 day.
}
echo json_encode($myJson);
And you can just do a simple iteration on your HTML code.
<script>
$.get("/", {ajax: true, pid: $('#metaSelect').val()}, function(success) {
//we can iterate through the success JSON!
var _dom = $('#dateSelectDiv').html(''); //just to clear it out.
for(var x in success) {
_dom.append("<option value='"+success[x].date+"'>"+success[x].formattedDate+"</option>");
};
}, "json");
</script>
So as you can see - you can pass alot of data using JSON
Maybe look at some of the documentation to - http://api.jquery.com/jQuery.get/ , http://api.jquery.com/jQuery.post/ - might give you more ideas.
Best of luck to you