$(document).ready(function(){
setInterval(function(){
$.ajax({ url: "getLiveData.php",
success: function(result){
$.each(result, function(i, result){
var t = $("table#insideTable");
t.append('<tr><td>' + result.carNo + '</td><td>' +
result.carSpeed + '</td></tr>');
});
},
dataType: "json"
});
}, 600000);
});
Hello, I was trying to use the code above to update car speeds for every 10 mins.
–data at 10:20AM—–
+-------+-------+
|car |speed |
+-------+-------+
|1 |170 kph|
+-------+-------+
|2 |150 kph|
+-------+-------+
|3 |190 kph|
+-------+-------+
–data at 10:30AM—–
+-------+-------+
|car |speed |
+-------+-------+
|1 |180 kph|
+-------+-------+
|2 |155 kph|
+-------+-------+
|3 |174 kph|
+-------+-------+
However, after running the code, the results obtained from the two time points are all shown, with one after the other (See below).
+-------+-------+
|car |speed |
+-------+-------+
|1 |170 kph|
+-------+-------+
|2 |150 kph|
+-------+-------+
|3 |190 kph|
+-------+-------+
|1 |180 kph|
+-------+-------+
|2 |155 kph|
+-------+-------+
|3 |174 kph|
+-------+-------+
What I really want is to have the new data from a later time to replace the current one.
+-------+-------+
|car |speed |
+-------+-------+
|1 |180 kph|
+-------+-------+
|2 |155 kph|
+-------+-------+
|3 |174 kph|
+-------+-------+
Can anyone help me?
Many thanks!
You want to use the
.html()function in place of.append():Change:
To:
Which will replace the HTML inside the table element rather than append to it. Here is a demonstration of using
.html()versus.append(): http://jsfiddle.net/jasper/TKaVF/Here is the documentation for
.html(): http://api.jquery.com/htmlOn a side-note, it doesn’t make your selector any faster by adding
tablesince you are looking-up an ID (which is quite fast on its own).Would be faster as: