1

I am asking for help relating to an earilier question. I have a script that makes a call to another script that returns data in a Json format.

The current script populates a html table created dynamically using JQuery. The issue I have is when another call for new/fresh data is made the data in the table is not getting updated/refreshed. It has been pointed out that the data is not getting updated because the script is using 'append' and I should be using html() or text(). The problem I have, I do not know where to start in changing my code so that each time a call for fresh data is made the displayed data is updated/overwritten. Can someone please help.

My code:

$(document).ready(function() {

function get_data() {
cache: false,   
  $.getJSON("get_data_logos.php", function(json){

  json = json[0].data;

  var tr ;
  for (var i = 0; i < json.length; i++) {
     // console.log(json[i].ClientImageName);

      tr = $('<tr/>');
      tr.css("border-bottom","2px solid #FFF");
      tr.append("<td width='15%'><div class='clientimage'><img src='../../../../conf_images/boards/" + json[i].ClientImageName + "'></></div></td>");
      tr.append("<td width='33%'><div class='clientname-text'>" + json[i].ClientName + "</div></td>");
      tr.append("<td width='33%'><div class='roomname-text'>" + json[i].RoomName + "</div></td>");
      tr.append("<td width='33%'><div class='time-text'>" + json[i].RoomFromTime + " - " + json[i].RoomToTime + "</div></td>");

   $('table').append(tr);
  }
  });

}

get_data();
setInterval(get_data,60000)
});

Many thanks.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
DCJones
  • 3,121
  • 5
  • 31
  • 53

1 Answers1

1

You need just to empty the table before appending the new data using .html() like :

$('table').html("");

Inside code will looks like :

$('table').html();

for (var i = 0; i < json.length; i++) {
     // console.log(json[i].ClientImageName);

      tr = $('<tr/>');
      tr.css("border-bottom","2px solid #FFF");
      tr.append("<td width='15%'><div class='clientimage'><img src='../../../../conf_images/boards/" + json[i].ClientImageName + "'></></div></td>");
      tr.append("<td width='33%'><div class='clientname-text'>" + json[i].ClientName + "</div></td>");

   $('table').append(tr);
  }

NOTE : Also remove cache: false, it has nothing to do in your function.

Hope this helps.

$(document).ready(function() {

  function get_data() {
    var tr ;
    var time = new Date();
    
    $('table').html("");
    
    for (var i = 0; i < 3; i++) {
        tr = $('<tr/>');
        tr.css("border-bottom","2px solid #FFF");
        tr.append("<td width='33%'><div class='clientname-text'>"+time+"</div></td>");

     $('table').append(tr);
    }

  }

  get_data();
  setInterval(get_data,1000)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table></table>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101