0

I checked several posts but I couldn't make it work. Here where I came so far:

myApp.controller('customersCtrl', function($scope, $http, $timeout) {
  var polling = function() {
    var value = $http({
      method: 'GET',
      url: 'poll.php'
    });

    value.success(function(data, status, headers, config) {
      $scope.records = data;
    });

    $timeout(function() {
      polling();
    }, 3000);
  };
  polling();
});
poll.php:
<?php 
$db = new mysqli('fdb4.freehostingeu.com', '1584066_users', '*******', '1584066_users');

if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}
$db->set_charset("utf8");
if(!$result = $db->query("SELECT * FROM mtp ORDER BY date DESC")){
    die('There was an error running the query [' . $db->error . ']');
} 

while($row = mysqli_fetch_assoc($result)){
    $row["date"] = strtotime($row["date"]) * 1000;
    $records[] = $row;
}
print( json_encode($records));
$result->free();
$db->close();
?>

It works on the first poll(); call but doesn't refresh if the SQL table updated from outside.

EDIT: I tried it by chance and somehow POST method worked in my case.

Litestone
  • 529
  • 7
  • 22

2 Answers2

0

When you use $interval or $timeout, then sometime you need to use $apply, try using $apply, it will work.

Here is your answer

myApp.controller('customersCtrl', function($scope, $http, $timeout) {
  var polling = function() {
    var value = $http({
      method: 'GET',
      url: 'poll.php'
    });

    value.success(function(data, status, headers, config) {
      $scope.records = data;
      $scope.$apply(); //Use $apply to start digest process manually.
       $timeout(function() {
         polling();
       }, 3000);
    });

  };
});
Laxmikant Dange
  • 7,606
  • 6
  • 40
  • 65
-1

You need $intervalinstead $timeout.

$timeout only wait 3 seconds and make a call then stops. With $interval you can instead wait 3 seconds, call the poll, wait 3 seconds, call the poll, etc...

myApp.controller('customersCtrl', function($scope, $http, $interval) {
  var polling = function() {
    var value = $http({
      method: 'GET',
      url: 'poll.php'
    });

    value.success(function(data, status, headers, config) {
      $scope.records = data;
    });

    $interval(function() {
      polling();
    }, 3000);
  };
  polling();
});
michelem
  • 14,430
  • 5
  • 50
  • 66
  • It loads on the first poll(), but doesn't refresh the html table even I update the SQL table from outside. Can it be because of jQuery mobile? May be scope data is updating but table isn't being refreshed? Am I missing $scope.$apply or a similar thing? – Litestone Jul 07 '15 at 06:13
  • Calling interval inside function which calls that function will cause memory leak – Laxmikant Dange Jul 07 '15 at 06:53