I need to add a class to some elements based on the time without page reload
I am creating this array when the page loads. I have a start time, an end time and an identifier.
$hrs = array(
array("2013-07-27 21:00", "2013-07-27 22:00", "one"),
array("2013-07-27 22:00", "2013-07-27 23:00", "two"),
array("2013-07-27 23:00", "2013-07-28 00:00", "three"),
);
Then I get the current time and grab the identifier from the array. I tried running this script in a separate file time.php using setInterval
but I can't pass $hrs
.
<ul>
<li class="one">1</li>
<li class="two">2</li>
<li class="three">3</li>
</ul>
var className = "<?php echo $class_name"; ?>
$(className).addClass("red");
what is the proper way of running this so I won't need to refresh the page? I did something like this but it alerts error:
* Working code below ****
<script>
var hrs = '<?php echo json_encode($hrs); ?>';
//get active class from time.php
$.ajax({
url : 'http://domain.com/time.php',
type : 'POST',
data : { val : hrs },
dataType : 'json',
success : function (result) {
className = result['current_class'];
},
error : function () {
alert("error");
}
})
</script>
time.php
$hrs = json_decode($_POST['val']);
date_default_timezone_set('Europe/Bucharest');
$date = date('Y/m/d H:i');
$test = strtotime($date);
$now = date("Y-m-d H:i", $test);
$class_name = "";
foreach ($_POST['val'] as $h) {
if ($h[0] <= $now and $now <= $h[1]) {
$class_name = $h[2];fa
break;
}
}
$class = array(
'current_class' => ( $class_name ),
);
echo json_encode($class);