getting different unix timestamps in php and javascript ( server time is wrong ) - javascript

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

Related

Jquery : Pass date from php format to a JS variable

i am receving start and end dates from a proc in following format
Array
(
[0] => Array
(
[min_created_date] => 2020-10-28 00:00:00.000
[max_created_date] => 2020-11-11 00:00:00.000
)
)
i have stored the values in below variables with the following outputs resepectively :
$start_range =$slider_range[0]['min_created_date'];
$start_range=substr($start_range, 0, strrpos($start_range, ' '));
$end_range= $slider_range[0]['max_created_date'];
$end_range=substr($end_range, 0, strrpos($end_range, ' '));
2020-10-28
2020-11-11
now i need to pass these dates to a jQuery function , i want to store this date to js variable since few js opetaions have to be performed to these dates further , Below is how i am trying to pass the dates
$(function() {
var startrange = <?php echo $start_range;?>;
var endrange = <?php echo $end_range;?>;
console.log(startrange+'startrange');
console.log(endrange+'endrange');
});
I get following in console :
1982startrange
1998endrange
please guide me how can i pass the dates to JS variables instead of <?php echo $date ?>
You have no other way to publish PHP variables in JavaScript without echo.
A cleaner way to do it to assign PHP variables to JavaScript vars inside a <script> tag so that PHP echo are not everywhere in your JS code.
<script type="text/javascript">
var startrange = '<?php echo $start_range; ?>';
var endrange = '<?php echo $end_range; ?>';
</script>
you have a lot of options, but i love unixtimestamp formats more ^^
PHP
$minCreatedDate = time();
$maxCreatedDate = strtotime('2020-11-11 00:00:00.000');
JS echoed in PHP file
var startrange = new Date(<?= $minCreatedDate ?> * 1000);
Date instance contains a lot of funcs. like "getDay", ...

Javascript check if PHP variable is defined or not

I can not find an answer to my problem and I am also not sure if this is possible or not.
Is there any way to check if a PHP variable is defined or not with javascript?
This is an example:
var op = <?PHP echo json_encode($op); ?>;
if $op is not defined I got an error in javascript:
Events:362 Uncaught SyntaxError: Unexpected token )
I understand this is normal because this variable does not exist in PHP. But there is a way to avoid the error if the variable does not exist?
Change:
var op = <?PHP echo json_encode($op); ?>;
To:
var op = <?PHP echo (!empty($op) ? json_encode($op) : '""'); ?>;
PHP is executed on the server, before the response is even sent to the user. Javascript is executed on the browser, once the user receives the response. So "communicating" in the way you describe is not possible. Just test in PHP if $op is empty, and output accordingly.
You can check it:
var op = <?php echo (isset($op) && $op) ? json_encode($op) : 'null'; ?>;
empty() is your best choice. http://php.net/manual/en/function.empty.php
var op = <?= !empty($op) ? json_encode($op) : '""' ?>;
Try like this :
var op = <?= isset($op) ? json_encode($op) : "" ?>;

how to convert strtotime in php to new Date in js

For a realtime countdown i use some php variables and echo them in the js like below:
$expire_year = '2016'; // year
$expire_month = '8'; // month ( 8 = August)
$expire_day = '14'; // day (14th)
$expire_hour = '2'; // hour ( 1-24)
$expire_minutes = '12'; // minutes
i use them in the js like blow:
timestamp = new Date(<?php echo $expire_year; ?>, <?php echo $expire_month - 1; ?>, <?php echo $expire_day; ?>, <?php echo $expire_hour; ?>, <?php echo $expire_minutes; ?>),
This works fine!
I use php strtotime to check if the date really has expired:
$quickpollexpiredate = strtotime("August 14, 2016 2:12"); // set an expiration date
So for the countdown timer in js and for the check in php, i have to use 2 different date "structures".
Is it possible to make a check in php so that i have to use only the 5 variables ($expire_year, $expire_month...) with strtotime() or another function?
So actually what i want to achieve is something like this (ofcourse this is wrong, but i hope you understand what i am trying to achieve)
$quickpollexpiredate = strtotime($expire_year, $expire_month, $expire_day, $expire_hour, $expire_minutes); // set an expiration date
If you have a timestamp in php, you can easily use it to set a Date object in javascript. You just need to consider that a timestamp in javascript is in milliseconds and not seconds like in php:
jsTimestamp = new Date(<?php echo $phpTimestamp; ?> * 1000);
or
jsTimestamp = new Date(<?php echo strtotime($yourDateString); ?> * 1000);
Note that new Date(...) also accepts strings, see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date for more details.

Make Button Clickable on predefined Time + Countdown in Button

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)

How can I pass multiple data from PHP to jQuery/AJAX?

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

Categories

Resources