I am getting some data from backend server and trying to put in the bootstrap table every 5 seconds. It is not able to display in table although I can clearly see the json object coming from backend in my console. I tried using refresh, load and append as well as first argument to bootstrapTable function but it is not helping. I want the new data to append to existing data when it comes from the backend in json format but the table is displaying as completely empty in the UI.
Javascript file
$(document).ready(function() {
getUpdates();
function getUpdates() {
$.ajax({
type: "GET",
contentType: "application/json",
url: "/getUpdates",
dataType: 'json',
cache: false,
timeout: 600000,
success: function (output) {
// var $table = $('#table');
$('#table1').bootstrapTable('refresh', {
data: output
});
console.log("SUCCESS : ", output); //this display correctly in console
},
error: function (e) {
var json = "<h4>Response:</h4><pre>"
+ e.responseText + "</pre>";
console.log("ERROR : ", e +"Response Text: "+ e.responseText);
// $("#btn-update").prop("disabled", false);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(getUpdates, 5000); // The interval set to 5 seconds
}
});
};
});
html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Updates through messaging</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="https://unpkg.com/bootstrap-table#1.14.2/dist/bootstrap-table.min.css">
<link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"/>
</head>
<body>
<div class="container" style="min-height: 500px">
<div class="starter-template">
<h1>CDC Consumer Example </h1>
<div class="container">
<table id="table1" data-height="450">
<thead>
<tr>
<th data-field="id">Id</th>
<th data-field="oldValue">Old Value</th>
<th data-field="newValue">New Value</th>
<th data-field="tableName">Table Name</th>
<th data-field="columnName">Column Name</th>
<th data-field="timestamp">Timestamp</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<script type="text/javascript"src="webjars/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="javascript/entry.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/bootstrap-table#1.14.2/dist/bootstrap-table.min.js"></script>
</body>
</html>
from looking at that libraries documentation I don't think that's how the refresh method works.
try something like this
$(document).ready(function () {
$('#table1').bootstrapTable({
url: '/getUpdates',
onLoadSuccess(data) {
setTimeout(getUpdates, 5000)
}
})
function getUpdates() {
$('#table1').bootstrapTable('refresh')
};
});
you have to use load not refresh in $('#table1').bootstrapTable('refresh',{data: output}); and just give your new data as a second parameter, for better understand you can see my example below(it's load every 5 seconds):
var mydata = [
{ id: 6521761346336241,
columnName: "sys_role_cd1",
newValue: "PARTY1",
oldValue: "PART1",
tableName: "entries1",
timestamp: 15550157197331
}];
$('#table1').bootstrapTable({data: mydata});
window.setInterval(function(){
//you can call your ajax and reload your table here
$(function () {
mydata.push({
id: 6521761346336242,
columnName: "sys_role_cd2",
newValue: "PARTY2",
oldValue: "PART2",
tableName: "entries2",
timestamp: 15550157197332
});
$('#table1').bootstrapTable('load',mydata);
});
//console.log("data reload",mydata);
}, 5000);
// to stop this loop you can use `clearInterval()`
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.js"></script>
<div class="container" style="min-height: 500px">
<div class="starter-template">
<h1>CDC Consumer Example </h1>
<div class="container">
<table id="table1" data-height="450">
<thead>
<tr>
<th data-field="id">Id</th>
<th data-field="oldValue">Old Value</th>
<th data-field="newValue">New Value</th>
<th data-field="tableName">Table Name</th>
<th data-field="columnName">Column Name</th>
<th data-field="timestamp">Timestamp</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
Related
i want to be to display child records when i click a button . The data is displayed as a table.
I have created a partial view that will display the records.
I have created a controller action method to return the partial view.
I have also added javascript code on the main page/view to call and load the dialog .
Here is the code for the main page/view
#model IEnumerable<LearningApp.ViewModel.Requistion>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
#{
ViewBag.Title = "Index";
}
</head>
<body>
<h4>Requistion List</h4>
<hr />
<table class ="table table-bordered"cellpadding="0" cellspacing="0" id="RequestGrid">
<tr>
<th>Request #</th>
<th>Date Made</th>
<th>Employee Name</th>
<th>Purpose</th>
<th>Directorate</th>
<th>Station</th>
<th></th>
</tr>
#foreach (var r in Model)
{
<tr>
<td>#r.RequestID</td>
<td>#r.RequestDate</td>
<td>#r.EmployeeName</td>
<td>#r.Purpose</td>
<td>#r.Directorate</td>
<td>#r.Station</td>
<td> <button type="button"class="ids" value="View Details" data-id="#r.RequestID"> View Details</button></td>
</tr>
}
</table>
<div id="dialog" title="View Requistion Details" style="overflow: hidden;">
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$("#dialog").dialog({
autoOpen: false,
width: 400,
modal: true
});
$('.ids').click(function () {
var requestid = $(this).data('id');
//alert("You clicked me...again" + requestid)
//var productId = $(this).data('id');
//alert(requestid)
$.ajax({
type: "POST",
url: "/tblRequistions/GetRequistionDetail",
data: '{RequestID: "' + requestid + '" }',
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$('#dialog').html(response);
$('#dialog').dialog('open');
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
</body>
</html>
Here is the controller method to return partial view.
[HttpPost]
public ActionResult GetRequistionDetail(int RequestID)
{
List<RequistionDetails> listofdetails = new List<RequistionDetails>();
listofdetails = r.getAllRequistionsDetails(RequestID);
return PartialView("_details",listofdetails);
}
If remove the portion of code below from the main view, and i run the page and i click on the button (view details) the ajax call to the controller is made and the correct parameter is passed.
$("#dialog").dialog({
autoOpen: false,
width: 400,
modal: true
});
If i leave it, nothing happens(ajax call not made).
I have tried to change autoOpen: True to see whether the dialog can open when the view loads, it does not load.
So i suspect the problem to be with the dialog.
Any reason why the dialog code is not working.?
Ronald
Take a look at this code:
$(function() {
function getDataById(u, n, tObj) {
if (n == undefined || isNaN(n)) {
return false;
}
var results = false;
console.log("AJAX, making request:", u, "ID:", n);
$.ajax({
type: "POST",
url: u,
data: {
RequestID: n
},
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function(r) {
results = r;
},
error: function(x, s, e) {
console.log("AJAX", s, e, x);
}
});
if (tObj != undefined) {
tObj.html(results);
}
return results;
}
$("#dialog").dialog({
autoOpen: false,
width: 400,
modal: true
});
$('.ids').click(function() {
var rHtml = getDataById("/tblRequistions/GetRequistionDetail", $(this).data('id'));
if (rHtml) {
$("#dialog").html(rHtml).dialog("open");
} else {
// Proof of Concept / Example Data
$("#dialog").html("**SAMPLE**<br />ID: 1, Date: 12/12/12, Name: Homer Simpson, Request: Donut, Director: Mr. Burns, Location: Plant").dialog("open");
}
});
});
<h4>Requistion List</h4>
<hr />
<table class="table table-bordered" cellpadding="0" cellspacing="0" id="RequestGrid">
<tr>
<th>Request #</th>
<th>Date Made</th>
<th>Employee Name</th>
<th>Purpose</th>
<th>Directorate</th>
<th>Station</th>
<th></th>
</tr>
<tr>
<td>1</td>
<td>12/12/12</td>
<td>Homer Simpson</td>
<td>Donut</td>
<td>Mr. Burns</td>
<td>Plant</td>
<td> <button type="button" class="ids" value="View Details" data-id="1"> View Details</button></td>
</tr>
</table>
<div id="dialog" title="View Requistion Details" style="overflow: hidden;">
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css" rel="stylesheet" type="text/css" />
I cannot test with AJAX. So I included Sample Data for the dialog as a proof of concept, yet the script does try to connect to AJAX and shows the error to console.
It's written to be used in a few ways. You can also do this:
getDataById("/tblRequistions/GetRequistionDetail", $(this).data('id'), $("#dialog"));
$("#dialog").dialog("open");
I don't advise this method. If the AJAX call is slow or details don't return, the dialog could open with no data.
I don't know, I can't read some JSON file ou put a table which read JSON data (internal or external source)
Does someone have an idea?
Here are my link and script I used
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.css">
<script src="https://unpkg.com/bootstrap-table#1.15.5/dist/bootstrap-table.min.js"></script>
Here is my script where I create the table, I use data-URL to load the data from a local JSON file
<table id="table" data-toggle="table" data-height="460" data-search="true" data-url="data.json">
<thead>
<tr>
<th data-field="id">#</th>
<th data-field="oeuvre" data-search-formatter="false" data-formatter="nameFormatter">Oeuvres</th>
<th data-field="type" data-formatter="nameFormatter">Type</th>
<th data-field="artist" data-formatter="nameFormatter">Artiste</th>
<th data-field="sheet" data-formatter="nameFormatter">Fiche</th>
</tr>
</thead>
</table>
<script>
$table.bootstrapTable('refresh',{data: data})
})
function nameFormatter(value) {
return 'Formatted ' + value
}
var $table = $('#table')
$(function() {
var data = [
{"id":1,"oeuvre":"choppe","type":"Ambre","artist":"Etienne","sheet":"<a href=\"description.html\">"}
]
$table.bootstrapTable({data: data})
})
</script>
I really don't know why it doesn't work...
thanks in advance
If you want to load a local json file, try like below.
function nameFormatter(value) {
return 'Formatted ' + value
}
var data = [
{"id":1,"oeuvre":"choppe","type":"Ambre","artist":"Etienne","sheet":"<a href=\"description.html\">"}
]
$("#table").bootstrapTable({data: data})
And remove data attribute data-url="data.json" from the table.
You can run the snippet below to see the results.
function nameFormatter(value) {
return 'Formatted ' + value
}
var data = [
{"id":1,"oeuvre":"choppe","type":"Ambre","artist":"Etienne","sheet":"<a href=\"description.html\">"}
]
$("#table").bootstrapTable({data: data})
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.css">
<script src="https://unpkg.com/bootstrap-table#1.15.5/dist/bootstrap-table.min.js"></script>
<table id="table" data-toggle="table" data-height="460" data-search="true">
<thead>
<tr>
<th data-field="id">#</th>
<th data-field="oeuvre" data-search-formatter="false" data-formatter="nameFormatter">Oeuvres</th>
<th data-field="type" data-formatter="nameFormatter">Type</th>
<th data-field="artist" data-formatter="nameFormatter">Artiste</th>
<th data-field="sheet" data-formatter="nameFormatter">Fiche</th>
</tr>
</thead>
</table>
If you want to load from an external source, your function should contain only the formatter function.
Try the snippet below to see the results.
function nameFormatter(value) {
return 'Formatted ' + value
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.css">
<script src="https://unpkg.com/bootstrap-table#1.15.5/dist/bootstrap-table.min.js"></script>
<table id="table" data-toggle="table" data-height="460" data-search="true" data-url="https://api.myjson.com/bins/q9n5g">
<thead>
<tr>
<th data-field="id">#</th>
<th data-field="oeuvre" data-search-formatter="false" data-formatter="nameFormatter">Oeuvres</th>
<th data-field="type" data-formatter="nameFormatter">Type</th>
<th data-field="artist" data-formatter="nameFormatter">Artiste</th>
<th data-field="sheet" data-formatter="nameFormatter">Fiche</th>
</tr>
</thead>
</table>
Remove the data-toggle attribute if you are not loading data from external json file.
It seems any calls to $('#table').bootstrapTable() are completely ignored when data-toggle is enabled and data is not rendered.
I put it in the variable already but it still gives me an error and it says uncaught reference error oTable is not defined
<script type="text/javascript">
$(document).ready(function(){
$("#test").click(function(){
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function( result ) {
var oTable = $("#datatable").DataTable({
processing: true,
data: result,
columns: [
{data: 'id'},
{data: 'title'}
]
});
}
});
});
$("#reload").click(function(){
oTable.DataTable().ajax.reload();
});
});
</script>
here is my html
<table id="datatable">
<thead>
<tr>
<th>ID</th>
<th>TITLE</th>
</tr>
</thead>
</table>
please help me Thanks
Hope this will work for you
Use Datatable Method to Load ajax,
No need to Initiate again to reload Datatble use oTable.ajax.reload();
I changed oTable to Global variable
$(document).ready(function () {
$("#reload").click(function () {
oTable.ajax.reload();
});
$("#test").click(function () {
window.oTable = $('#datatable').DataTable({
"ajax": {
"url": "https://jsonplaceholder.typicode.com/posts",
"dataSrc": ""
},
"columns": [{
"data": "id"
},
{
"data": "title"
},
]
});
});
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type='text/javascript'>
</script>
</head>
<body>
<button id="reload">
reaload
</button>
<button id="test">
test
</button>
<div class="container">
<table id="datatable">
<tr>
<th>ID</th>
<th>TITLE</th>
</tr>
</thead>
</table>
</div>
your oTable variable definition was on onSuccess callback, so it can't call from outside of onSuccess callback scope
I am using Angularjs as the frontend and spring mvc as the backened for my application. I am using datatables for displaying records. The problem I am facing is datatables works sometimes and sometimes doesn't.
After performing edit or delete or any dynamic operations the datatable loses its shape like pagination, filtration, search. Even though there will be data but it shows there are no records but still it displays records with no pagination.
I tried draw() and reload methods in the script but nothing seemed to work.
In html pages my order of loading css and js files are like this
<html lang="en" data-ng-app="adminApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" media="screen" href="resources/front/css/bootstrap.css">
<link rel="stylesheet" type="text/css" media="screen" href="resources/front/css/Custom-Style.css">
<link rel="stylesheet" type="text/css" media="screen" href="resources/front/font-awesome-4.0.3/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" media="screen" href="resources/front/font-awesome-4.0.3/css/font-awesome.css">
<link rel="stylesheet" type="text/css" media="screen" href="resources/front/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" media="screen" ref="resources/front/css/responsive.dataTables.min.css">
<link rel="stylesheet" href="resources/angular/angulars-datetime-picker.css" />
<link rel="stylesheet" href="resources/front/css/spinner.css">
<script src="resources/front/js/jquery-1.12.4.js" type="text/javascript"></script>
<script src="resources/front/js/bootstrap.js" type="text/javascript"></script>
<script type="text/javascript" src="resources/front/js/Custom-js.js"></script>
<script src="resources/front/js/jquery.dataTables.js" type="text/javascript"></script>
<script type="text/javascript" src="resources/front/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="resources/front/js/dataTables.responsive.min.js"></script>
</head>
</html>
This is the script where I tried everything. I have placed this inside the head tag. I have placed all the above code in every html file.
<script>
$(document).ready(function() {
$('#example').DataTable();
});
</script>
Here is how i am using ng-repeat for displaying data in table
<div class="TableBox">
<table id="example" class="display responsive nowrap"
cellspacing="0" width="100%" >
<thead>
<tr role="row">
<th class="sorting_asc" tabindex="0" aria-controls="example"
rowspan="1" colspan="1" aria-sort="ascending" aria-label="" >
SlNo
</th>
<th class="sorting_asc" tabindex="0" aria-controls="example"
rowspan="1" colspan="1" aria-sort="ascending"
aria-label="">Name</th>
</tr>
</thead>
<tbody>
<tr role="row" class="even" data-ng-repeat="student in students">
<td>{{$index + 1}}</td>
<td>{{student.studentName}}
</td>
</tr>
</tbody>
</table>
</div>
Here is my AngularController.js
$scope.getAllStudents = function()
{
AdminStudentService.getAllStudents().then(function(response)
{
$scope.students=response.data;
});
}
Here is my update method
$scope.updateStudent = function(student)
{
$scope.editstudentForm.$submitted= true;
if($scope.editstudentForm.$valid)
{
AdminStudentService.updateStudent(student).then(function(response)
{
if(response.data=="success")
{
$scope.editstudentForm.$submitted= false;
$window.scrollTo(0,0);
$scope.student = {};
$scope.getAllStudents();
$scope.successmessage1="Student Details Updated!;
$timeout(function()
{
$scope.closeeditStudent();
$scope.successmessage1="";
}, 1500);
}
});
}
}
Am I missing something in the script or do I need to add something?
I'm providing you with .js function that will help you understand datatables.
$scope.getAllReports = function() {
$http({
method : 'GET',
url : '/getReport'
}).success(function(data, status, headers, config) {
$scope.test = data;
$('#stack').DataTable().clear().draw();
angular.forEach($scope.test, function(test) {
$('#mantisi').DataTable().row.add([
test.t0,
test.t1,
test.t2,
test.t3,
test.t4,
test.t5
]).draw();
});
});
};
Also here is code from .html:
<table id="stack" class="table table-bordered table-striped" ng-init="getAllReports()">
<thead>
<tr>
<th>t0</th>
<th>t1</th>
<th>t2</th>
<th>t3</th>
<th>t4</th>
<th>t5</th>
</tr>
</thead>
<tbody></tbody>
</table>
And also a .js for DT:
$('#stack').DataTable({
"order": [[ 0, "asc" ]],
"language": {
url: '/datatables/datatables.hr.json'
},
"drawCallback": function( settings ) {
$(".btn-excel-custom").removeClass("dt-button buttons-excel buttons-html5");
$(".btn-default-custom").removeClass("dt-button").addClass("btn btn-default");
},
"bPaginate": false,
dom: 'Bfrt',
buttons: [{
text:"Export to Excel",
extend: 'excel',
className: 'btn btn-excel-custom'
}]
});
These are 3 main snippets for decent show-up of jQuery datatables. Also, I've created special methods provided by DT API in last snippet.
I am trying to use this table to display table that contains data that are loaded from a .csv file.
Is there a way to load data from .csv into this table with the capability of applying conditional formatting ?
Thanks!
The following code is as far as iv could up to now, the table body <tbody> is separated from the table.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="1000">
<!-- REFRESH EVERY 2 minutes -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://papaparse.com/resources/js/papaparse.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/datatables/1.9.4/css/demo_table.css">
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/datatables/1.9.4/css/jquery.dataTables.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/datatables/1.9.4/jquery.dataTables.min.js"></script>
<style type="text/css">
</style>
<title>HTML TABLE FROM .CSV DATA SOURCE</title>
</head>
<body>
<script>
//Setting data.csv as data source to be loaded into table id="example"
$(function() {
Papa.parse("data.csv", {
download: true,
complete: function(example) {
console.log("Remote file parsed!", example.data);
$.each(example.data, function(i, el) {
var row = $("<tr/>");
row.append($("<td/>").text(i));
$.each(el, function(j, cell) {
if (cell !== "")
row.append($("<td/>").text(cell));
});
$("#example tbody").append(row);
});
}
});
});
</script>
<script type='text/javascript'>
//Conditionally formating. Where North office are red and South office are green
//<![CDATA[
$(window).load(function() {
$('#example').dataTable({
"fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
switch (aData[0]) {
case 'North':
$(nRow).css('color', 'red')
break;
case 'South':
$(nRow).css('color', 'green')
break;
}
}
});
}); //]]>
</script>
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
You have to somehow transform your .csv into an array of arrays [[]](each element representing an array of columns), like in the example given in the tutorial on the page shown.
The data key of the configuration object, you pass to datatables as to have the value of this structure.
An example to bruteforce converting would be in this fiddle:
var csv="1,2,3\n4,5,6"
function csvToArray(csv){
return csv.split('\n').map(function(x){
return x.split(',');
})
};
console.log(csvToArray(csv));
For proper parsing rely on a parsing library.