ajax auto update table with json data - javascript

hello and right at the beginning, I still have not much experience with js or jquery but I am still working on my skills.
I have a table and the data in the table are coming from an external json file, to which I have no influence.
creating the table works fine, but the next step is to refresh the data in the table every "x" seconds.
I have done some research but i could not find any solutin till now.
the table it self:
<table class="table table-hover">
<thead>
<tr>
<th>Number</th>
<th>Sign</th>
<!--<th>Group</th>-->
<th>Location</th>
<th>N</th>
<th>E</th>
<th>On position</th>
<th>Ignition on</th>
<th>Moving</th>
</tr>
</thead>
<tbody id="vehicleList">
</tbody>
</table>
the code, which creates the table is the following:
$(document).ready(function() {
refreshTable();
$.getJSON(getshowObjectReportExtern, function(data){
var vehicleListData = '';
$.each(data, function(key, value){
vehicleListData += '<tr id="rowVehicleStatus" class="">';
vehicleListData += '<td>'+value.objectno+'</td>';
vehicleListData += '<td>'+value.objectname+'</td>';
//vehicleListData += '<td>'+value.objectgroupname+'</td>';
vehicleListData += '<td>'+value.postext_short+'</td>';
vehicleListData += '<td>'+value.latitude_mdeg+'</td>';
vehicleListData += '<td>'+value.longitude_mdeg+'</td>';
vehicleListData += '<td>'+value.pos_time+'</td>';
vehicleListData += '<td>'+value.ignition+'</td>';
vehicleListData += '<td>'+value.standstill+'</td>';
vehicleListData += '</tr>';
});
$('#vehicleList').append(vehicleListData);
});
function refreshTable(){
$('#vehicleList').load(getshowObjectReportExtern, function(){
setTimeout(refreshTable, 5000);
});
});
the result at the moment is, that the table will be created but after the first reload the raw json data will be added to the table.
has anybody any advice for me?
thanks in advance!

setTimeout does, as the name suggestes, wait a period of time before executing. setInterval however creates a interval caller that is ran every n seconds. You have to change your signature method to that.
However, you have another function. Because you don't remove the previous dynamically added entries from the table before you append, you will append the same rows every time the interval runs. To avoid this, you should assign some class to the tbody or something of your table, then clear this before adding the content back. This ensures that the content of the json file is not added multiple times.
$(document).ready(function() {
// Fetch the initial table
refreshTable();
// Fetch every 5 seconds
setInterval(refreshTable, 5000);
});
function refreshTable(){
$.getJSON(getshowObjectReportExtern, function(data) {
var vehicleListData = '';
$.each(data, function(key, value) {
vehicleListData += '<tr id="rowVehicleStatus" class="">';
vehicleListData += '<td>'+value.objectno+'</td>';
vehicleListData += '<td>'+value.objectname+'</td>';
//vehicleListData += '<td>'+value.objectgroupname+'</td>';
vehicleListData += '<td>'+value.postext_short+'</td>';
vehicleListData += '<td>'+value.latitude_mdeg+'</td>';
vehicleListData += '<td>'+value.longitude_mdeg+'</td>';
vehicleListData += '<td>'+value.pos_time+'</td>';
vehicleListData += '<td>'+value.ignition+'</td>';
vehicleListData += '<td>'+value.standstill+'</td>';
vehicleListData += '</tr>';
});
// We use .html instead of .append here, to make sure we don't add the same
// entries when the interval is ran for the n-th time.
$('#vehicleList').html(vehicleListData);
});
}

If you want to refresh your table for every x seconds, you should use setInterval() function instead.

Related

last modified date after edit function

I want to display a "Last modified time" in my javascript table. I have searched a lot on date time but I can only find the last modified time on the document. I have some variables in my table (see below question). What i want to do is display the date after i was modified that variable. Can anyone help me ? :)
The table what im using with javascript.
`
if(response.length > 0)
{
for (var count = 0;count < response.length; count++)
{
html += '<tr>';
html += '<td>' +response[count].id+'</td>';
html += '<td>€'+response[count].inkoopprijs+'</td>';
html += '<td>€'+response[count].verkoopprijs+'</td>';
html += '<td>' +response[count].producten+'</td>';
html += '<td>' +response[count].create_date+'</td>';
html += '<td>' +response[count].last_modified+'</td>';
html += '<td><a href="../prijswijzigen.php?edit='+response[count].id+'" class="edit_btn">Edit</td>';
html += '<td><a onclick="return confirm()" href="crud.php?del='+response[count].id+'" class="del_btn">Delete</td>';
html += '</tr>';
serial_no++;
}
}
`
html += '<td>' +response[count].last_modified+'</td>';
That line is for my variable last modified that is the same as my create_date variable.
The DOM lastModified property in HTML. That displayed the time of the last time i modified the file.
new Date().toLocaleDateString()
is that what you need?

The html td is not updating via jquery

I have this little method which, on the first load, created a <tr> and some <td>'s. That works. But if the underlying data changes, the <td>'s are not updated. I'm not sure why.
function ParseJson(json, isFirstLoad)
{
json = $.parseJSON(json);
var tr;
for (var i = 0; i < json.length; i++) {
if (isFirstLoad === 1)
{
tr = $('<tr/>');
tr.append("<td id='" + json[i].LocationName + "'>" + json[i].LocationName + "</td>");
tr.append("<td id='" + json[i].LocationName + "Count'>" + json[i].Count + "</td>");
$('#MainTable').append(tr);
}
else
{
var td = $("#" + json[i].LocationName + "Count");
td.html = json[i].Count;
}
}
When isFirstLoad is 1, the html is rendered as I would expect. Example:
<tr>
<td id="ChemLab">ChemLab</td>
<td id="ChemLabCount">24</td>
</tr>
But the next time around, if the data has changed and someone has left the Chem Lab, the html for ChemLabCount does not change.
I have verified that the json being passed into this method is correct. Meaning, the count DOES indeed change. It just doesn't get displayed on the screen.
jQuery .html() is a function, not a property.
td.html(json[i].Count);
The problem comes from td.html = json[i].Count; because it's not the right way of using html() method.
To set the Count to your td you could use .text() instead :
td.text( json[i].Count );
Else if you want to set an HTML code the you could use .html() :
td.html( json[i].Count );

Table rows are not rendering on separate lines

I am trying to render a table, wherein each row of data is on a separate line. From my understanding, this is the default behavior for how data between <tr></tr> tags is rendered. At least, that is how it is has always functioned for me.
This is the code I am using:
function GetLastTen(){
$.ajax({url: LastTen, success: function(result) {
var location = document.getElementById('l_ten');
location.innerHTML = "<table>\n";
function format(location,object){
location.innerHTML += '<tr>\n' +
'<td>' + object.id + '</a></td>\n' +
'</tr>\n';
}
$.each(result, function(elem){
format(location, result[elem]);
});
location.innerHTML += "</table>"
}});
}
The code obtains the proper data--there is nothing wrong with what I am getting from the API endpoint, but all the rows are on the same line.
I am using bootstrap 3.3.7 and the latest version of jQuery.
Try constructing a HTML string first into variable and setting the innerHTML once you are done:
var result = [{id:1},{id:2},{id:3}]
$(document).ready(function(){
var location = $("#l_ten")
var tableHTML = "<table>\n"
function format(object){
tableHTML += '<tr>\n<td>' + object.id + '</a></td>\n</tr>\n';
}
$.each(result, function(elem){
format(result[elem]);
});
location.html(tableHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="l_ten"></div>

How to append table head only once when loop through the JSON

How to only once append table head when looping(search) through the JSON array?When I try this, every time when starting search table-head append for every match, although two products belong the same group.
HTML
</select>
Search: <input type="text" name="search" id="search" />
<div id="place"></div>
Java Script
$.ajaxSetup({ cache: false });
$('#search').keyup(function(event){
$('#place').html('');
if (event.keyCode == 8) {
$('#place').hide('')
}else{
$('#place').show('')
}
$('#state').val('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
LOOP JSON
$.getJSON('product.json', function(result) {
//LOOP JSON
TABLE HEAD to appears only once in the search.
$.each(result, function(key, value){
//TABLE HEAD this need to apperas only one
var text = '';
text +='<table class="table" width="610" cellpadding="3"
cellspacing="1" bgcolor="#cccccc">';
text +='<tr>';
text +='<th width="20%" bgcolor="#aaaaaa" align="left"><font
color="#ffffff">Model</font></th>';
text +='<th width="25%" bgcolor="#aaaaaa"><font color="#ffffff">CODEC
Supported</font></th>';
text +='</tr>';
text +='<p style="font-size:15px; font-weight:bold; color:#2773ba;
margin-bottom:5px">'+value.brand+'</p>';
// END TABLE HEAD
//END OF TABLE HEAD -START TABLE BODY
// TABLE BODY is filling with data from json
if (value.brand.search(expression) != -1 ||
value.model.search(expression) != -1 ||
value.CODECSupported.search(expression) != -1 )
{
text += '<tr>'
text += '<td colspan="9" align="left" bgcolor="#FFFFFF" style="font-
weight:bold; color:#3399cc">'+value.type+'</td>'
text += '</tr>'
text += '<tr>'
text += '<td bgcolor="#FFFFFF">'+value.model+'</td>'
text += '<td align="center"
bgcolor="#FFFFFF">'+value.CODECSupported+'</td>'
text += '</tr>'
text += '</table>'
$('#place').append(text)
}
});
});
});
END OF BODY
})
You can either do the table creation outside of the loop (have just the generated data inside the loop), or you can have a boolean that checks whether you have went through the loop once
Example pseudo-ish code:
passed = false;
for(i=0;i<10;i++){
// some code happening
if(!passed){
// here add the headers
passed = true;
}
else{
//do the rest
}
// other code happening
}
I would recommend having the table setup outside the loop since it would be more efficient, because with this pseudo code you will have an extra check on each iteration of the loop.
Hope this helps!

I want to sort my table column on input value AFTER setting value

Newb here...I have a table I created using the jQuery DataTables plugin. Everything is working as expected BUT I added a column that is an input. I'd like for users to be able to sort this column after putting in their values. It is a ranking system that is using quite a long list of items so they need to be able to sort after entering values so that they can keep track of what numbers they've used up to that point. I am setting my variable to be the input value on keyup but after I set the value, I can't sort the column by clicking on the header. It works for the other columns (from jQuery DataTable plugin). Also, if i hard code some text before if the td (before '+sortRank+') it also works as expected. Why is it not recognizing the values for sorting after I set them with jQuery? Thanks for you help!
$(document).ready(function() {
function GenerateTableFromJson(objArray,objArrayTwo,objArrayThree) {
var tableContent = '<table summary="GFSTechIntake" id="AllRequestsTable" style="width:100%"><thead><tr><th>Submit Priority</th><th>Your Prev Rank</th><th>Current Overall</th><th>Category</th>' + '<th>Status</th>' +' <th>Request Name</th>' + '<th>Problem Statement</th>' + '<th>Business Benefits</th><th>Dept(s)</th></tr></thead><tbody>';
var sortRank = "";
$('input.title').on('keyup',function(){
sortRank = $(this).val();
});
tableContent += '<tr class="allItemsTr">';
if(rank != ''){
tableContent += '<td class="allItemsPriority">'+sortRank+'<input class="title" placeholder=' + rank + ' value='+rank+'></td>';
} else {
tableContent += '<td class="allItemsPriority"><input class="title" placeholder=' + rank + '></td>';
}
tableContent += '<td class="prevRank">N/A</td>';
tableContent += '<td class="currentRank">N/A</td>';
}
return tableContent;
}

Categories