With jQuery's $.post i want to send a value to my php function , where inside it should lookup the events by it's current selected month.
Now there some programmatic problems.
First is to what value it is best to make the check against.
In theory i have all available, but the ideas i have all seem to be clumsy.
If it helps , i use the following script that does all the calculation with the data i provide it with. eventCalendar
For my testing purposes , just to make a check if the event is active or not i use the following code:
var Calendar = new Object();
Calendar.id = '1';//Check if active 1 or 0
var calendarJson = JSON.stringify(Calendar);
$('#indicator').show();
$.post('Controller.php',
{
action: 'get_events',
calendar: calendarJson
},
function(data, textStatus) {
....more code
Were the data is retrieved and handled as:
public function getEvents($calendar){
$sth = $this->dbh->prepare("SELECT * FROM events WHERE current = ?");
$sth->execute(array($calendar->id));
return json_encode($sth->fetchAll());
}
Where in the counted result the most important data = event_sdate varchar(255)
looks like:
event_sdate = 1394220775280 (milliseconds)
However my intention is to let it send back all events by it's given month.
So i have to replace current = ? with something that is inserted when create a new event.
And that should, at least it is what i think, the month and year of creation.
And when make the call to the php function:
Calendar.id = '1';//Check if active 1 or 0
Should be something like:
Calendar.id = 'March 2014';//Check if current month and year
When i load the calendar without any events yet it looks like:
this jsfiddle
I hope someone could point me in the right direction of how to achieve what i try to do
It seems i answered my own question.
Should be something like:
Calendar.id = 'March 2014';//Check if current month and year
Generated HTML contains required values:
<div id="eventCalendarInline" data-current-year="2014" data-current-month="2">
in jQuery:
var currentYear= $('#eventCalendarInline').data("current-year");
var currentMonth = $('#eventCalendarInline').data("current-month");
var Calendar = new Object();
Calendar.month = currentMonth;
Calendar.year = currentYear;
And in php:
public function getEvents($calendar){
$sth = $this->dbh->prepare("SELECT * FROM events WHERE cyear = ? AND cmonth = ?");
$sth->execute(array($calendar->year, $calendar->month));
return json_encode($sth->fetchAll());
}
Related
I need help creating a counter that starts from 1 value (2000000) and ends at 2nd value (2500000), resets every day and does not restart upon page load.
I was able to get almost exactly what I want with javascript - but this restarts on page load/refresh. I imagine I need to write this in PHP, but I can't figure out how - any help/pointers would be awesome.
Here is the javascript example on JSfiddle and below:
var start = 200000001;
var end = 250000000;
var interval = 578;
var refreshIntervalId = setInterval(function(){
if(start <= end){
$("#start").text(start++);
}else{
stop();
}
},interval);
function stop(){
clearInterval(refreshIntervalId);
}
it's possible to solve you problem with ajax function and get the value from a database.
if you want use Cronjob and php for your probelm and dont work with database , use text file .
save your current number in a text file , i write a function for you a sample below :
function yourfunction($start,$end){
$perv = file_get_contents("num.txt");
if($perv <= $end){
$current = $perv++;
file_put_contents("num.txt","$current");
}
}
I want to use flipclock for the reverse counter. The timer should start from hh:mm:ss (eg, 19:40:46) to 00:00:00.
Below is the code
var clock;
$(document).ready(function() {
// Grab the current date
var currentDate = new Date();
// Set some date in the future. In this case, it's always Jan 1
var futureDate = new Date(currentDate.getFullYear() + 1, 0, 1);
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
// Instantiate a coutdown FlipClock
clock = $('.dw_clock').FlipClock(diff, {
clockFace: 'DailyCounter',
countdown: true,
showSeconds: true
});
});
I don't want the date. Also, the time values should get fetched from MySQL and are different for different users when they log in. From PHP-MySQL, I have:
function timeToPlay(&$smarty){
$sqlStr = "select timediff('24:00:00', time(taken_on)) as timeRemaining,
hour(timediff('24:00:00', time(taken_on))) as hour,
minute(timediff('24:00:00', time(taken_on))) as minute,
second(timediff('24:00:00', time(taken_on))) as second
FROM profile_sicc_exer_score where user_id=".$_SESSION['user_id']."
order by id desc limit 1";
$sqlQuery = mysql_query($sqlStr) or die(mysql_error()."<hr>".$sqlStr);
if ( mysql_num_rows($sqlQuery) ) {
$timeToPlayNext = mysql_fetch_assoc($sqlQuery);
$smarty->assign("timeRemaining",$timeToPlayNext['timeRemaining']);
$smarty->assign("hour",$timeToPlayNext['hour']);
$smarty->assign("minute",$timeToPlayNext['minute']);
$smarty->assign("second",$timeToPlayNext['second']);
}
}
From the above code, I get the values of (example)
$timeRemaining = 19:40:46
$hour = 19
$minute = 40
$second = 46
How do I use the values in the above Flipclock code which is javascript/jquery...
For flipClock, you have to change the clockFace to "HourlyCounter", so it doesn't show the date.
After that, having the php variables, you can "echo" them into the javascript code, for example, at the end of the webpage, you can put:
<script>
clock.setTime(<?php echo $hour*3600+$minute*60+$second; ?>);
</script>
You can always put it in an "onload" function or something like that, but it should work fine with that.
You didn't left any details about the actual html page where the counter is showing, so I can't help you further this.
Good luck!
In PHP I have used below code to get the time of US.
date_default_timezone_set('UTC');
$dateTimeZoneLA = new DateTimeZone("America/Los_Angeles");
$dateTimeLA = new DateTime("now", $dateTimeZoneLA);
Now I need to add validation of datetime using jQUery but how can I match the US time with the calender time. time using jQUery. Below is the code I have used in jQuery. But it did not workk acc. to US time.
var starttime = $('#dateTime').val();
var present = new Date(now);
var firstDate = new Date(starttime);
if(present.getTime() > firstDate.getTime()){
$('#dateTime').after('`<ul class="errors"><li>Sorry, but you cannot add past date.</li></ul>`');
}
I'm fairly new to PHP and really new to JQuery.
So I writ some JQuery that does some calculations, I writ something below that is similar:
//on change of a selectbox with the class item
$('.item').change(function() {
// set variable id as the id name of this id
var id = this.id;
// price variable is equal to the value of the element id 'hiddenprice'
price = $("#hiddenprice").val();
// number of items is the value of the select box
numberofitems = $(this).val();
// number of days is equal to a php variable I set on the page
numofdays = "<?php echo $length->days; ?>";
//totalprice is equal to the 'price' multiplied by 'numofdays'
totalprice = Number(price) * Number(numofdays);
//calculates final total by multiplying the 'totalprice' by 'numofitems'
finaltotal = Number(totalprice ) * Number(numofitems);
//updates the HTML with the new price
$('#'+id).html("€" + finaltotal.toFixed(2));
});
I was trying this and although I got it to work, after reading up some I am aware that because this script is in my footer of the page that is getting updated, it is unsafe and easy to manipulate if a user wanted to be malicious.
So I want to do the calculations server side, by posting values to a PHP script and then returning the values.
// POST values to PHP Script
$id = (posted select id);
$price = (#hiddenprice variable value);
$numofitems = (posted value of the select);
$numofdays = $length->days;
$totalprice = (int)$price * (int)$numofdays;
$finaltotal = (int)$totalprice * (int)numofitems;
//Then push $finaltotal and $id back to the user viewed page
$('#'+<?php echo $id; ?>).html("€" + <?php echo $finaltotal; ?>.toFixed(2));
I'm just not sure how to push them to the page without refresh and then return them, also without refresh.
Again, sorry if this is simple, I have looked at JQuery form plugins, I just wondered if there is more apt solution for what I would like to do.
Thanks in advance.
You may want to check out ajax, it can post or get data without refreshing the page. Also the answer of this question may be helpful too.
You need to use AJAX. This sends data to the server and allows you to execute a callback once you receive a response.
If you are using jQuery, then read up about the $.ajax method.
To handle the response, the easiest data type to use is JSON.
So a quick example
Javascript
$.ajax({
url: calculation_url.php,
method: 'post',
dataType: 'JSON',
data: {price: price, days: numofdays },
success: function(response) {
// you should check a valid response was received
$("#result").html(response.html);
}
});
PHP - calculatin_url.php
$price = $_POST['price'];
$days = $_POST['days'];
// do calculations
// send data back as json
die(json_encode(array('html' => $finalTotal)));
To start this process you will need to attach events to the calculation button. Read about registering events with the on method and you may find it helpful to read about the event.preventDefault() method.
So here's what I'm trying to do - I have the following code:
<div id="on">
<p>We are: <span class="onair">ON AIR</span></p>
</div>
<div id="off">
<p>We are: <span class="offair">OFF AIR</span></p>
</div>
And what I'd like to do is "show" the "on" div on Tuesday's from 3pm to 4pm (server time), while simultaneously hiding the "off" div - and then switch that around for every other date/time.
?
If you use PHP you can do logic statements on the server-side to render the exact information you need instead of calculating it later on the client side.
(Client side solutions work too if you dont care about where the time is coming from)
(1) You can have the server render javascript for you that you can use in a script
//if you want the server's time you can do this:
<?php $timestamp = time(); ?>
//render variables in javascript instead of html
<?php
echo <<<EOD
<script>
var timestamp = ${timestamp}
//then later in your javascript process the timestamp logic to update the dom
</script>
EOD;
?>
(2) You can also have the server render a className in the body tag based on whether or not a condition is true or false. (This is my preferred method usually)
//onAirClass( min, max, timestamp ) returns className
//this function returns onair or offair class if the timestamp is in range
function onAirClass( timeMin, timeMax, timestamp ){
if( timestamp >= timeMin && timestamp <= timeMax ){
return 'onair';
}
return 'offair'
}
//using onAirClass( min, max, timestamp )
<?php $bodyClass = $bodyClass . ' ' . onAirClass( $timestamp ); ?>
<?php echo "<body class='${bodyClass}'>"; ?>
then in your styles you can have the elements you want to hide or show based on class inheritance from the body tag.
Check out the PHP time function to create new time strings, and do time calculations for your onAirClass() function
How to check the time between a given time range
UPDATED
Corrected PHP syntax errors
#maerics solution is OK, depending on what you want to do, just don't EVER do anything like this:
var timestamp = $('#server-timestamp').text();
Ultimately, there are many ways to do the same thing, but some things are more 'right' than others.
There are reasons to do some calculations on the client side vs the server side, and vice versa. As a newbie developer, just make sure that whatever method you use:
is simple
is efficient (doesnt do anything unnecessary or redundant)
falls in line with best practices
Actually this can be accomplished using just JavaScript without any server-side code, by using your timezone offset.
Here's a function you can use:
var onAir = function (day, start, end, timezone) {
var local, utc, show, days, onAir, startValues, endValues, startTime, endTime, startMinutes, endMinutes, showMinutes;
// by default, we are not on air
onAir = false;
// map day numbers to indexes
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Firday', 'Saturday'];
// convert start/end times to date objects
startValues = start.split(':');
endValues = end.split(':');
startTime = new Date();
endTime = new Date();
startTime.setHours(startValues[0], startValues[1]);
endTime.setHours(endValues[0], endValues[1]);
// add the hours minutes together to get total minutes
startMinutes = (startTime.getHours() * 60) + startTime.getMinutes();
endMinutes = (endTime.getHours() * 60) + endTime.getMinutes();
// get the current local time
local = new Date();
// get the current time in the show's timezone
utc = local.getTime() + (local.getTimezoneOffset() * 60000);
show = new Date(utc + (3600000*timezone));
// convert the show hours + minutes to just minutes
showMinutes = (show.getHours() * 60) + show.getMinutes();
// test to see if the show is going on right now
if (days[show.getDay()] === day && (showMinutes >= startMinutes && showMinutes <= endMinutes)) {
onAir = true;
}
return onAir;
}
// example: Air time is Tuesday between 1-2pm Central Time (-6)
var texasShowOnAir = onAir('Tuesday', '13:00', '14:00', '-6'));
// now check if we are on air
if (texasShowOnAir) {
// do stuff here...
}
You can now use this function like this:
var check = onAir('DAY', 'STARTTIME', 'ENDTIME', 'YOURTIMEZONE');
This will return a true/false. Be sure and use 24 hour format.
I would even argue that this is better than using your server's timestamp, because often (especially if you have shared hosting), your server can be set in a different timezone than you.
Here's a demo fiddle: http://jsfiddle.net/stevenschobert/mv54B/
Have the server provide a timestamp when it generates the page and have the client also generate a timestamp when it loads the page so that you can calculate the time offset between the two systems.
Then you can call a function on some interval that checks the current server time to see if it is within the 3pm-4pm period and show/hide the target elements as needed.
From the server:
<div id="server-timestamp" style="display:none">2013-02-12T18:01:19Z</div>
On the client:
$(document).on('load', function() {
var serverTime = new Date($('#server-timestamp').text())
, clientTime = new Date()
, offsetMilliseconds = (clientTime - serverTime);
setInterval(function() {
// If server time is 3pm-4pm then hide/show divs...
}, 1000 /* every second */);
});