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);
Replace:
var hrs = '<?php echo $hrs; ?>';
To:
var hrs = '<?php echo json_encode($hrs) ?>';
If you are sending data using POST
type : 'POST',
You have to access it using $_POST
, you are using $_GET
.
$_POST['val']
Neither language has any clue about the internals of the other language, your best bet to pass a full array is to encode the AJAX side array to JSON, pass that to your PHP script, and then use json_decode to decode it into a PHP array.
You could also try passing the parameters with square brackets on the end, with the same name as php interprets this as an array. i.e.
file.php?p[]=1&p[]=2&p[]=3&p[]=4&p[]=5
Would result in $_GET['p']
being a 5 item array containing 1 - 5.
The same is also true of post, if you post multiple p[]
's, you will end up with $_POST['p']
as an array of all your elements.