1

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?

2
  • 1
    Your code won't work. PHP is executed only once when loading the page. Use api.jquery.com/jquery.ajax & call the api to refresh several times Commented May 3, 2017 at 9:12
  • 2
    That's because the location is output once when the page is initially served. If you want it to be dynamic, you need call a separate PHP script asynchrously every 3 seconds to retrieve the new location. Commented May 3, 2017 at 9:12

1 Answer 1

2

Have you used third party Web-service It's may be possible they manage cache for same request with same parameters and domain.

I mean if you can call API with same parameters and same domain service provider return you data which are cached on your first call.

You need to pass "Cache-Control: no-cache" in header of cUrl call

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Authorization: Bearer $key",
    "Cache-Control: no-cache",
));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.