0

JSON example:

[{
    "client": "client1",
    "ip": "127.0.0.1",
    "status": "up"
}, {
    "client": "client2",
    "ip": "127.0.0.2",
    "status": "up"
}]

I have this script to read the JSON file and create tables and apply color to tables according to JSON information:

<script type="text/javascript">

    $.getJSON("<urltojson>/clients.json",
    function (data) {

        var tr;
        for (var i = 0; i < data.length; i++) {
            tr = $('<tr/>');
            tr.append("<td>" + data[i].client +  "</td>");
            $('table').append(tr);

           if(data[i].status == "up")
            {
              $('td',tr).css ('background-color', '#88d066');
             } else {
              $('td',tr).addClass("statusHOSTDOWN");
            };
        }
    });

    </script>

The JSON file itself gets updated through a backend python script. Everything works as intended. However, if I want to see update information from JSON file I need to hard-reload the webpage, which is pretty easy to do. But I want javascript to auto reload JSON in the background and apply conditions gracefully without a hard reload of the webpage.

It's probably something trivial to do , but my lack of js knowledge is not helping me. I did a couple of hours worth research without any luck. Any help is appreciated.

bran
  • 167
  • 1
  • 3
  • 12
  • who is triggering $.getJSON? – brk Aug 10 '16 at 14:22
  • If you want the data to change on the client when it changes on the server, you'll need either ... polling, server sent events, or websockets. – adeneo Aug 10 '16 at 14:23
  • You need to put your code in a function, figure out what you want to use as a trigger (button click, timer, etc), and call the function when that event occurs. – Jason P Aug 10 '16 at 14:23
  • no one is. the script is in the header, loading the site gets triggered. – bran Aug 10 '16 at 14:23
  • Can't you just wrap your code in a Timeout / Interval? See: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval – Mike Scotty Aug 10 '16 at 14:23
  • Search for "long polling": http://stackoverflow.com/questions/11077857/what-are-long-polling-websockets-server-sent-events-sse-and-comet – André Dion Aug 10 '16 at 14:23
  • Well, you already have a $.getJSON() function which uses AJAX, now you need something to call that function within an interval: `setInterval()` https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval – yuriy636 Aug 10 '16 at 14:23
  • The code examples I got so far didn't work at all (I have come to similar results in my research). I am looking into long polling now. I think there might be another issue of new result not replacing the previous result inthe table just amending at the bottom of the table. – bran Aug 10 '16 at 15:23

3 Answers3

1

You can simply call your function, and related getJSON jQuery method every 3 seconds with an interval as such;

window.setInterval(function(){ getJson(); myFunc(); }, 3000);
Laçin Yavuz
  • 106
  • 3
  • I am getting this error on browser inspect console: `7 Uncaught TypeError: getJson is not a function` – bran Aug 10 '16 at 15:04
1

You can use setInterval or setTimeout to fetch JSON every few seconds.

var timeToRefresh = 5 * 1000; // 5 seconds
setTimeout(function fetchData() {
  $.getJSON("<urltojson>/clients.json",
    function (data) {

        var tr;
        for (var i = 0; i < data.length; i++) {
            tr = $('<tr/>');
            tr.append("<td>" + data[i].client +  "</td>");
            $('table').append(tr);

           if(data[i].status == "up")
            {
              $('td',tr).css ('background-color', '#88d066');
             } else {
              $('td',tr).addClass("statusHOSTDOWN");
            };
        }
    });
  setTimeout(fetchData, timeToRefresh);
}, timeToRefresh);

I know that isn't a perfect solution but i hope it will works.

legendemil
  • 146
  • 4
  • Hello I have tried this before. Instead of updating the existing table, it just appends more table at the bottom of the previous and goes on and on. Not ideal of course. – bran Aug 10 '16 at 15:05
0

You are creating table in your code, but this object is not displayed on your page. Try like this:

var timeToRefresh = 5 * 1000; // 5 seconds
setTimeout(function fetchData() {
  $.getJSON("<urltojson>/clients.json",
    function (data) {

        var tr;
        for (var i = 0; i < data.length; i++) {
            tr = $('<tr/>');
            tr.append("<td>" + data[i].client +  "</td>");
            $('#myTable').append(tr);

           if(data[i].status == "up")
            {
              $('td',tr).css ('background-color', '#88d066');
             } else {
              $('td',tr).addClass("statusHOSTDOWN");
            };
        }
    });
  setTimeout(fetchData, timeToRefresh);
}, timeToRefresh);

html

 <table id="myTable"></table>
tata.leona
  • 1,060
  • 11
  • 17
  • Same issue as @emil Pausz code. and yes I forgot to add table on my example but it was properly used on my working code. – bran Aug 10 '16 at 15:06