I was trying to create a dynamic table with contents from jQuery. Also I have enabled a setTimeout in order for the data to be refreshed and updated in the html page.`
$(document).ready(function update_data() {
$.ajax({
dataType: "json",
url: "/wirelessSensor/dag",
success: updateForData,
error: errorOnAjax
});
setTimeout(function() {
update_data();
}, 5000);
});
function updateForData(data) {
// Updates DAG
console.log("Wirless nodes details");
var hasData = true;
if (data.result && data.result && data.result == "none") {
console.log('No data in result');
hasData = false;
} else if (!data.devices || !data.status) {
console.log('Devices not found in result');
hasData = false;
}
if (hasData) {
console.log('Creating Table');
var trHTML = '';
$.each(data.devices, function(index) {
trHTML += "<tr><td>" + data.devices[index] + "</td><td>" + data.lifetime[index] + "</td><td>" + data.status[index] + "</td></tr>";
});
$("#location").append(trHTML);
}
}
function errorOnAjax(jqxhr, status, errorstr) {
var errText = (errorstr == null) ?
'' : ', error: ' + errorstr;
console.log('Ajax error: ' + status + errText);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="location" border='1' width='100%'>
<tr>
<th align='center'> Devices </th>
<th align='center'> Lifetime </th>
<th align='center'> Status </th>
</tr>
</table>
Here since am using setTimeout my dynamic table is getting duplicated. The entries already existing are been repeated. How can I avoid this?
You can restructure your HTML to include <thead> and <tbody> elements, and the set the contents of the <tbody> to the results (rather than appending results to entries that might already be present).
<table id="location" border='1' width='100%'>
<thead>
<tr>
<th align='center'> Devices </th>
<th align='center'> Lifetime </th>
<th align='center'> Status </th>
</tr>
</thead>
<tbody id="location-content"></tbody>
</table>
Then do $("#location-content").html(trHTML); (note: html instead of append, to destroy old results instead of keeping them)
Related
I am working in Modern SharePoint and have a web-part installed that allows me to inject code directly into the page. I have built this code to allow me to use a DataTable to pull information from a List I have on that site.
I am having trouble with the filters for the columns as they appear to not be pulling in any values at all. I believe this is due to me calling the data for the table after the DataTable has been created. But I also reference the table in the code to get the data for the table after it is declared. Can someone please take a look at my code and see if there is a way for this to be done?
Any help would be appreciated!
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Image</th>
<th>Title</th>
<th>Industry</th>
<th>Market</th>
<th>Description</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Image</th>
<th>Title</th>
<th>Industry</th>
<th>Market</th>
<th>Description</th>
</tr>
</tfoot>
</table>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<link
rel="stylesheet"
type="text/css"
href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css"
/>
<script>
var dataTable;
$(document).ready(function () {
dataTable = $('#example').DataTable({
initComplete: function () {
this.api()
.columns([2, 3])
.every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.header()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>');
});
});
}
});
$.ajax({
url:
"https://ewscripps.sharepoint.com/sites/lighthouseideas/_api/web/lists/getbytitle('Site%20Pages')/items?$select=FileLeafRef,Title,Industry,Market,Description,PageType&$filter=TaxCatchAll/Term eq 'Station Initiatives'",
headers: {
accept: 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'X-RequestDigest': jQuery('#__REQUESTDIGEST').val()
},
success: function (data) {
console.log('issued URL Request');
//Get Success Stories
for (var i = 0; i < data.d.results.length; i++) {
console.log('Found: ' + data.d.results[i].Title);
dataTable.row
.add([
"<img src='https://ewscripps.sharepoint.com/sites/lighthouseideas/_layouts/15/getpreview.ashx?path=SitePages/" +
data.d.results[i].FileLeafRef +
"'>",
data.d.results[i].Title,
data.d.results[i].Industry.results,
data.d.results[i].Market.results,
data.d.results[i].Description
])
.draw(false);
}
console.log(data.d.results[4]);
console.log(data.d.results[9]);
dataTable.draw(true);
}
});
});
</script>
This should be related to databind after DataTable init, try to update the init with data, in your case, it's success function.
You could check my previous tested thread here.
I have a form that includes a checkbox that when clicked performs an AJAX request to update a backend database. I would like to then remove the checkbox input and replace it with a a simple table cell showing the current date.
Here's my form:
$(document).ready(function() {
$("input[name='dateReceived']").change(function() {
var recid = $(this).closest('td').attr('id');
// Create a reference to $(this) here:
$this = $(this);
$.post('updateAsset.php', {
type: 'updateAsset',
recid: recid,
dateReceived: dateReceived
}, function(data) {
data = JSON.parse(data);
//console.log( data );
if (data.error) {
var ajaxError = (data.text);
var errorAlert = 'There was an error updating the Date Received - ' + ajaxError + '. Please contact the Help Desk';
$this.closest('td').addClass("error");
//display AJAX error details
$("#dateReceivedErrorMessage").html(errorAlert);
$("#dateReceivedError").show();
return; // stop executing this function any further
} else {
$this.closest('td').addClass("success")
$this.closest('td').removeClass("error");
// if you want to show a success alert enable the following
// $("#ajaxAlert").addClass("alert alert-success").html(data.text);
}
}).fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an error updating the Date Received - AJAX request error. HTTP Status: ' + httpStatus + '. Please contact the Help Desk';
// console.log( 'ajaxError: '+ajaxError );
$this.closest('td').addClass("error");
//display AJAX error details
$("#dateReceivedErrorMessage").html(ajaxError);
$("#dateReceivedError").show();
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-condensed table-striped table-bordered">
<thead>
<th class="text-center" scope="col">ID</th>
<th class="text-center" scope="col">Code</th>
<th class="text-center" scope="col">Description</th>
<th class="text-center" scope="col">Received</th>
<th></th>
</thead>
<tbody>
<tr class="" id="111202">
<td>GRP423423</td>
<td>BWEQRQEW/A</td>
<td>Standard Containers</td>
<td id="111202"><input type="checkbox" id="111202" value="1" class="form-control" name="dateReceived"></td>
</tr>
<tr class="" id="111216">
<td>GRP424213412</td>
<td>PPUPJHL/A</td>
<td>Packaging Boxes</td>
<td id="111202"><input type="checkbox" id="111202" value="1" class="form-control" name="dateReceived"></td>
</tr>
</tbody>
</table>
which is currently working fine and adding the success/danger class accordingly. If it is successful I would like to extend this to replace the checkbox input with a simple table cell showing the current date, e.g.
DD/MM/YYYY
I think you can achieve it by adding this into your success function:
$(this).hide();
var dd = new Date();
$(this).closest('td').append(dd.getDate() + '/'+ ('0' + (dd.getMonth() + 1)).slice(-2) + '/'+ dd.getFullYear());
I Think you can change your td's html instead of appending to achieve it
$(this).hide();
var dd = new Date();
$(this).closest('td').html(dd.getDate() + '/'+ ('0' + (dd.getMonth() + 1)).slice(-2) + '/'+ dd.getFullYear());
My table tbody doesn't display the correct data after an AJAX GET request. Well actually, after the second iteration of my for loop, it is showing correctly, but after the third iteration and so on, it is appending but it is showing the previous item.
This is what it showing:
I don't know why it is showing incorrectly in the table in console log, the data is showing correctly.
$.ajax({
cache: false,
type: 'GET',
url: '#Url.Action("DisplayFiles","FileUploader")', //url, // '/Account/Delete/',
dataType: "json",
success: function(response) {
$("#tblFiles tbody").remove();
for (var i = 0; i < response.length; i++) {
console.log(response[i]['Filename']);
console.log(response[i]['FileFullPath']);
$("#tblFiles").append('<tr><td>' + response[i]['Filename'] + '</td><td>' + response[i]['FileFullPath'] + '</td></tr>');
//var tbodyFiles = "<tr><td> " + response[i]['Filename'] + "</td>" + "<td> " + response[i]['FileFullPath'] + "</td></tr>";
}
//$("#tblFiles").append(tbodyFiles);
console.log(response);
},
error: function(resp) {
console.log('error');
}
});
<table class="table table-striped" id="tblFiles">
<thead>
<tr>
<th>Filename</th>
<th>File Fullpath</th>
#*
<th>Date Added</th>*#
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Filename)
</td>
<td>
#Html.DisplayFor(modelItem => item.FileFullPath)
</td>
#*
<td>
#Html.DisplayFor(modelItem => item.DateAdded)
</td>
*#
<td>
#Html.ActionLink(" ", "Delete", new { id = item.Id }, new { #class = "btn-xs btn btn-danger glyphicon glyphicon-trash" })
</td>
</tr>
}
</tbody>
</table>
Change this:
$("#tblFiles tbody").remove();
to this:
$("#tblFiles tbody tr").remove();
and then change this:
$("#tblFiles").append(...)
to this:
$('#tblFiles tbody").append(...)
Explanation:
You were removing the entire tbody element, but appending the trs to the table not the tbody.
The proposed changes will ensure that the tbody stays present and that trs are added as children to it instead of outside of it.
I'm use table JSon. But I have encode it from php to Json.
So I just call file pin.php from tables.
example my HTML tables:
HTML:
<table
data-url="../../tables/pin.php"
data-row-style="rowStyle"
data-toggle="table"
data-show-refresh="true"
data-show-toggle="true"
data-show-columns="true"
data-search="true"
data-select-item-name="toolbar1"
data-pagination="true"
data-sort-name="name"
data-sort-order="desc">
<thead>
<tr>
<th data-field="id_pin" data-sortable="true" data-align="center">ID PIN</th>
<th data-field="no_meja" data-sortable="true" data-align="center">Nomor Meja</th>
<th data-field="status" data-sortable="true" data-align="center">Status</th>
<th data-field="action" data-sortable="true" data-align="center">Input Pemesanan</th>
</tr>
</thead>
<tr>
</tr>
</table>
Script table :
<script>
$(function () {
$('#hover, #striped, #condensed').click(function () {
var classes = 'table';
if ($('#hover').prop('checked')) {
classes += ' table-hover';
}
if ($('#condensed').prop('checked')) {
classes += ' table-condensed';
}
$('#table-style').bootstrapTable('destroy')
.bootstrapTable({
classes: classes,
striped: $('#striped').prop('checked')
});
});
});
function rowStyle(row, index) {
var classes = ['info', 'info', 'info', 'info', 'info'];
if (index % 2 === 0 && index / 2 < classes.length) {
return {
classes: classes[index / 2]
};
}
return {};
}
</script>
Question: I want this table is auto refresh.
please help me this one.
It looks like you're using Bootstrap Tables. According to the documentation, you can refresh the table, so just set a timer to do it periodically:
(function(){
function refreshTable() {$('#table-style').bootstrapTable('refresh', {silent: true});}
setInterval(refreshTable, 5000);
})()
I am trying to add a dynamic row to the existing table on click of button, whose rows are dynamically created using output from PHP script.
I doing an ajax call to the script insert_tr.php which returns me a TR element in the same format as the existing table with the data.Data is returned appropriately
But unfortunately, the <tr> row is not being added to the table dynamically but adds only after a page refresh.
PHP file code :
<div id="v_div">
<table class="table table-bordered table-striped" >
<thead>
<th class='col-md-2'>name</th>
<th class='col-md-2'>number</th>
</thead>
<tbody>
<?php
while ($data = pg_fetch_assoc($ret)) {
echo
"<tr id=tr_".$data['sr_number'].">
<td class='td_topic' id=title:".$data['number']." >".trim($data['name'])."</td>
<td class='td_topic' id=title:".$data['number']." >".trim($data['number'])."</td>
<td class='td_topic' id=title:".$data['number']." ><button class='btn btn-info check1' type=button title='Add Entry'>Add Entry</button></td>
</tr>";
?>
</tbody>
</table>
</div>
Javascript :
$(document).ready(function() {
$("#v_div").on('click', '.check1', function() {
var field_userid = $(this).parent().attr("id");
var value = $(this).text();
$.post('insert_tr.php', field_userid + "=" + value, function(data) {
if (data != '') {
$(this).closest("tr").after(data);
}
});
});
});
All I want to do is add the row immediately after the current TR am on ,dynamically without a page refresh, which serves the ultimate use of an ajax call.
The reference to this is not the button that was clicked.
$(this).closest("tr").after(data);
Store a reference to the row outside the Ajax call.
$(document).ready(function() {
$("#v_div").on('click', '.check1', function() {
var field_userid = $(this).parent().attr("id");
var value = $(this).text();
var row = $(this).closest("tr");
$.post('insert_tr.php', field_userid + "=" + value, function(data) {
if (data != '') {
row.after(data);
}
});
});
});