I am trying to update a value from a server every 3 seconds but I'm having a very strange behavior with the following code:
PHP function
function getLocation($key, $car_id) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://owner-api.teslamotors.com/api/1/vehicles/$car_id/data_request/drive_state");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer $key"
));
$dat = curl_exec($ch);
curl_close($ch);
$result = json_decode($dat, true);
$lat = $result['response']['latitude'];
$long = $result['response']['longitude'];
return array($long, $lat);
}
Javascript call:
<script>
function refreshLocation() {
try {
<?php
$loc = getLocation('someToken', 'someID');
?>
pos = [<?php echo '"'.implode('","',$loc ).'"' ?>];
pos[0] = parseFloat(pos[0].replace(",", "."));
pos[1] = parseFloat(pos[1].replace(",", "."));
console.log("Loc:" + pos[1] + " : " + (pos[0]));
}
catch(err) {
}
setTimeout(refreshLocation, 3000);
}
</script>
The problem is, no matter how the value changes on the server, the getLocation function always returns the same value as it does when executed the first time. Only a refresh of the whole page gives a new value. I cannot see the problem and I'm not able to find a satisfying solution to this. Is there a problem with PHP and javascript I don't realise?