I am trying to get the server date and time using an Ajax call. I am able to retrieve the value I need, but when I try to use it to create a javascript date object, I get an invalid date error. I tried to use trim to remove any spaces too. Any ideas?
Ajax call:
// ajax call to getcurrent server time
$.ajax({
type: GET',
url: 'datetime.php',
success: function(data) {
console.log("Data: " + data);
currentdate = new Date($.trim(data));
console.log("Current date from server: " + currentdate);
},
});
PHP Code:
<?php
echo date('y,m,d,H,i,s');
?>
Console Output (Chrome):
Data: 12,06,08,15,07,57
Current date from server: Invalid Date
You are trying to use a string as if it were literal code. Kind of like using
eval, but without actually including theeval.Yes,
evalis one way to do it:currentdate = eval("return new Date("+$.trim(data)+");");However
evalis evil. Instead, you should do:Even better, though, would be to have your PHP script be
echo time();, then your JS could be: