Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Wendell Pulsipher
10,183 PointsJavascript timer with Ajax not working properly
The following code is supposed to act like an automatic clock feature that updates every second and shows the user how long the user has been logged in and how much they will be charged based on that time. It works as far as putting the data on the page, but it doesn't update every second automatically.
Here is my ajax:
var total_time_logged;
function timepay(){
$.ajax({
url: "scripts/time_pay.php",
}).done(function(data){
var info = $.parseJSON(data);
$('.time-fee').html("Time: "+info.time+" -- Cost: $"+info.fee);
});
}
window.setTimeout(timepay(),1000);
and here is my php
$user = $_COOKIE['cookiename'];
$login_time = $_COOKIE['login_time_for_'.$user];
$total_time_logged = time() - $login_time;
$total_fee = $total_time_logged / 60 / 60 * 25;
$date = new DateTime();
$date->setTimestamp($total_time_logged);
$hours_str = $total_time_logged / 60 / 60;
$hours_arr = split('[.]', $hours_str);
$hours = $hours_arr[0];
$minutes_str = $total_time_logged / 60;
$minutes_arr = split('[.]', $minutes_str);
$minutes = $minutes_arr[0];
if($hours[0] == 0){
$time = $date->format('00:i:s');
}if($minutes[0] == 0){
$time = $date->format('00:00:s');
}if($minutes[0] != 0 && $hours[0] != 0){
$time = $date->format('H:i:s');
}
$fee = substr($total_fee, 0, 5);
$data = array('time'=>$time, 'fee'=>$fee);
echo json_encode($data);
1 Answer
Wendell Pulsipher
10,183 PointsFound the solution. I switched it over to setInterval and I shouldn't have been calling "timepay()" as a function but rather as a variable to be returned as a value -> "window.setInterval(timepay, 1000);"