Angularjs polling to create realtime feed

I am new to angularjs and want to create a page which is nearly realtime.

I would like to poll a php file which queries a database and returns the latest results as json to to added to the feed.

I have created a controller for the page and made it update every 5 seconds.

discussionApp.controller('ViewCtrl', function($scope, $interval /* , $location, $http */) {
    console.log("View Controller");
    $scope.pageClass = 'page-view';

    $scope.data = "";
    $interval(function() {
        //update $scope.dataevery 5000ms
        $scope.data = new Date();
    }, 5000);

});

Open in new window



I have managed to get it on the view

        {{data | date : 'medium'}}

Open in new window


I just need some guidance on the best way to get the data via php.
Steve TinsleyAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Radek BaranowskiFull-stack Java DeveloperCommented:
It's just a little bit off topic, but you can consider using thing like firebase to work as a database for your AngularJS app. It gives you live bi-directional coupling between your page and data model, without worrying about php. (https://www.firebase.com/docs/web/libraries/angular/quickstart.html)
Alexandre SimõesManager / Technology SpecialistCommented:
Inside your setInterval you have to do an ajax call to get the data.

I'm not a PHP developer but you can look at some examples on the web.
On the Angular side you need something like:
$http.get('yoururl', { action: 'getfeeddata' })
    .success(function(data){
        // do something with data
    });

Open in new window


On the PHP side I believe you need something like:
if($_GET['action'] == "getfeeddata") {
  echo json_encode("your data");;
}

Open in new window

Steve TinsleyAuthor Commented:
Thanks Alex,

Ive got it sort of working

discussionApp.controller('ViewCtrl', function($scope, $interval, $http /* , $location,  */) {
    console.log("View Controller");
    $scope.pageClass = 'page-view';

    $interval(function() {
        console.log("polling");

        $http.get('getData.php')
            .success(function(data) {
                $scope.contents = data;
            });

    }, 5000);

});

Open in new window



How would I go about appending each loop to the last??
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Alexandre SimõesManager / Technology SpecialistCommented:
So you want to each time you do the request, you want to add to what you already have?
        $http.get('getData.php')
            .success(function(data) {
                Array.prototype.push.apply($scope.contents, data);
            });

Open in new window

I'm assuming that $scope.contents and data are an arrays
Steve TinsleyAuthor Commented:
So the last thing Im not sure how to do is remember the last ID added and pass it as a parameter to my PHP script so I don't get the same row twice.

Should I get it from the table row ID?? or remember it in a global variable??
Alexandre SimõesManager / Technology SpecialistCommented:
Don't you have it in the $scope.contents ?
Can't you simply pick the last item in this list and pass it to the ajax request?

If the list is empty, just pick everything.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Steve TinsleyAuthor Commented:
How do I do this??
Steve TinsleyAuthor Commented:
Think I got there:

discussionApp.controller('ViewCtrl', function($scope, $interval, $http /* , $location,  */) {
    console.log("View Controller");
    $scope.pageClass = 'page-view';

    $scope.contents = [];
    lastID = "0";

    $interval(function() {

        $http.post('getData.php?id='+lastID)
        .success(function(data, status) {
            //$scope.contents = data;

            if (data != undefined) {
                Array.prototype.push.apply($scope.contents, data);

                lastID = $scope.contents[$scope.contents.length - 1].discussionID;
                console.log("LAST ID: "+lastID);
            }
        })
        .error(function (data, status) {
            console.log("ERROR: "+status)
            $scope.status = status;
        });


    }, 5000);

});

Open in new window

Alexandre SimõesManager / Technology SpecialistCommented:
Just a couple of remarks:

1. lastID variable is declared on top without the var keyword.
This makes it a global variable. To avoid at any cost! :)
If for instance, in another piece of code you also declare a variable with the same name, in the same way (without the var), they will both be pointers to the same variable and override themselves. This is a nightmare to debug.
So, replace line 6 with:
var lastID = "0";

Open in new window


2. Probably is just for test, but don't leave console.log calls in the code.
the console object is a global object, and the way javascript works, it has to go up through the whole scope tree until it actually finds it attached to the window object.
This is another thing to avoid. Depending where it is, it can actually affect the performance in a significant way.

Apart from that, looks good :)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.