JavaScript AJAX Basics (retiring) Programming AJAX Processing JSON Data

EMILIO RAFAEL HERNANDEZ PEREZ
EMILIO RAFAEL HERNANDEZ PEREZ
7,966 Points

json in realtime

Hello, I really like it But, do you want to know if it is possible to pass the data in real time? Let the widget.js read every 5 seconds and if you modify the .json the li is modified

2 Answers

Helmut Granda
Helmut Granda
10,343 Points

The answer is yes and there are different methods, the easiest that you could test is by setting a timer on your script to request data every 5 seconds, if the data has changed you can also change the DOM. In addition you can pause the timer while you parse and display the data to avoid issues with data being requested or rendered before the time is needed.

Enjoy!

EMILIO RAFAEL HERNANDEZ PEREZ
EMILIO RAFAEL HERNANDEZ PEREZ
7,966 Points

Perfect, thank you very much. This code works ok and is updated every 5 seconds

widget.js

function carga() {
  $.getJSON('../data/employees.json', function (data) {
    var statusHTML = '<ul class="bulleted">';
    $.each(data,function (index, employee) {
      if (employee.inoffice === true) {
        statusHTML +='<li class="in">';
      } else {
        statusHTML +='<li class="out">';
      }
      statusHTML += employee.name + '</li>';
    });
    statusHTML += '</ul>';
    $('#employeeList').html(statusHTML)
  }); // end getJSON
}); // end ready

setInterval(carga,5000);