Il Chulio
Il Chulio

Reputation: 31

PHP cURL returns old data when called multiple times from javascript

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?

Upvotes: 1

Views: 1234

Answers (1)

Krupal Patel
Krupal Patel

Reputation: 1497

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",
));

Upvotes: 2

Related Questions