A_Elric
A_Elric

Reputation: 3568

Knockout.js update values from mysql database

Let's assume that I have 3 computers that write to a mysql database based on whether they are online or offline every 5 minutes.

I display this information on a website in a simple html table and read the mysql database with php.

The output goes something like this:

<table>
    <th>Computer portfolio</th>
    <tr>
        <td>Computer Name</td>
        <td>Status</td>
        <td>Last Connected</td>
    </tr>
    <tr>
        <td>Computer 1</td>
        <td>Okay</td>
        <td>2013-07-10 00:15:25</td>
    </tr>
    <tr>
        <td>Computer 2</td>
        <td>Down</td>
        <td>2013-07-08 00:15:25</td>
    </tr>
    <tr>
        <td>Computer 3</td>
        <td>Okay</td>
        <td>2013-07-10 00:17:25</td>
    </tr>
</table>

The php code is really easy and is just returning a select * from db then iterating through the array.

My question is simply, how do I incorporate knockout to reload the results from the DB every 5 minutes to refresh the items on the page.

Upvotes: 1

Views: 2436

Answers (1)

Brigand
Brigand

Reputation: 86240

CodePen Demo

function getJSON(callback) {
    // Get an array from the server
    // callback(data)
}

Create a view model with an observable array. Then make a refresh method that pulls data, and overrides the observable. Because all items in the array are dependant on the root array, there's no need for them to be observable.

function ViewModel(){
  var self = this;
  self.items = ko.observableArray([]);

  self.refresh = function(){
    getJSON(function(data){
      self.items(data);
      console.log(data);

    });
  }

Refresh once, and then again at the desired interval, e.g., 5 minutes.

  self.refresh();
  setTimeout(self.refresh, 5 * 60 * 1000);
}

ko.applyBindings(app = new ViewModel);

jQuery provides very easy AJAX methods, such as $.getJSON.

function getJSON(callback) {
    $.getJSON('tabledata.php', callback);
}

Also, there's a plugin called Live, which syncs data in real time between multiple clients. However it depends on NodeJS, so it may not be a good solution to you (mostly posting it here for future-googlers.

Upvotes: 1

Related Questions