DataTables does not display data - javascript

I'm trying the jQuery DataTables control. The problem is that I cannot display data.
HTML is:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DataTablesTest.aspx.cs" Inherits="JsonTest.DataTablesTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DataTables Test</title>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<link href="Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<script src="Scripts/DataTables/jquery.dataTables.js"></script>
<link href="Content/Site.css" rel="stylesheet" />
</head>
<script>
var d = [
{ "Id": 3, "ActivityID": 91, "OperationType": 0, "UserID": 4183, "Comments": "", "ActionDate": "2006-03-19T12:26:01.673" },
{ "Id": 4, "ActivityID": 91, "OperationType": 4, "UserID": 4183, "Comments": "", "ActionDate": "2006-03-19T12:26:01.673" },
{ "Id": 5, "ActivityID": 92, "OperationType": 0, "UserID": 5688, "Comments": "", "ActionDate": "2006-03-20T12:05:40.563" }
];
$(document).ready(function () {
$('#example').dataTable({
"ajax": {
"url": "WebService1.asmx/GetData",
"type": "POST",
"dataSrc": "",
"contentType": "application/json; charset=utf-8"
},
//"data": d,
"columns": [
{ "data": "Id" },
{ "data": "ActivityID" },
{ "data": "OperationType" },
{ "data": "UserID" },
{ "data": "Comments" },
{ "data": "ActionDate" }
]
});
var table = $('#example').DataTable();
alert('There are' + table.data().length + ' row(s) of data in this table');
});
</script>
<body>
<form id="form1" runat="server">
<div>
<table id="example" class="display">
<thead>
<tr>
<th>ActivityHistoryID</th>
<th>AH_ActivityID</th>
<th>AH_OperationType</th>
<th>AH_UserID</th>
<th>AH_Comments</th>
<th>AH_TimeStamp</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
</html>
If I comment out the Ajax code and uncomment the
//"data": d,
It works fine. The d variable is the JSON data that I get from the service using firefox->developer->network->xhr->response dialog.
I read many posts and I tried many things but I can't make it work.
Any help?
Thanks.
EDIT:
Service Code:
namespace JsonTest
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string GetData()
{
var list = ActivityHistory.GetAll(); // List<ActivityHistory>
var s = Newtonsoft.Json.JsonConvert.SerializeObject(list);
return s;
//return "{\"aaData\":" + s + "}";
}
}
}
EDIT 21/07/2015:
I've done some changes in HTML code and it's working with a little bug. While loading I see for a moment at the top of the page the headers of the table element (ActivityHistoryID, AH_ActivityID, AH_OperationType, AH_UserID, AH_Comments, AH_TimeStamp). After that it's working fine (for 60.000 rows!!!).
The new-changed code is:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DataTablesTest.aspx.cs" Inherits="JsonTest.DataTablesTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DataTables Test</title>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<link href="Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<script src="Scripts/DataTables/jquery.dataTables.js"></script>
<link href="Content/Site.css" rel="stylesheet" />
<script>
$(document).ready(function () {
$.ajax({
type: "post",
url: "WebService1.asmx/getdata",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = $.parseJSON(data.d);
$('#example').DataTable({
"data": myData,
"columns": [
{ "data": "Id" },
{ "data": "ActivityID" },
{ "data": "OperationType" },
{ "data": "UserID" },
{ "data": "Comments" },
{ "data": "ActionDate" }
]
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="example" class="display">
<thead>
<tr>
<th>ActivityHistoryID</th>
<th>AH_ActivityID</th>
<th>AH_OperationType</th>
<th>AH_UserID</th>
<th>AH_Comments</th>
<th>AH_TimeStamp</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
</html>
My last hope is that I 'm using JQuery 1.10.2 instead of 1.11.1 which is in the examples of datatables site.
It 's the third day of trying and still I cannot figure it out.
EDIT 22/7/2015
That is the code that works. Far from examples.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DataTablesTestWorking.aspx.cs" Inherits="JsonTest.DataTablesTestWorking" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DataTables Test</title>
<script src="Scripts/jquery-1.11.3.min.js"></script>
<link href="Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<script src="Scripts/DataTables/jquery.dataTables.js"></script>
<link href="Content/Site.css" rel="stylesheet" />
<script>
$(document).ready(function () {
$('#example').hide();
$.ajax({
type: "POST",
url: "WebService1.asmx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#example').show();
var myData = $.parseJSON(data.d);
$('#example').DataTable({
"data": myData,
"columns": [
{ "data": "Id" },
{ "data": "ActivityID" },
{ "data": "OperationType" },
{ "data": "UserID" },
{ "data": "Comments" },
{ "data": "ActionDate" }
]
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="example" class="display">
<thead>
<tr>
<th>ActivityHistoryID</th>
<th>AH_ActivityID</th>
<th>AH_OperationType</th>
<th>AH_UserID</th>
<th>AH_Comments</th>
<th>AH_TimeStamp</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
</html>

Modify your ajax call - make it asynchronous
"ajax": {
"url": "WebService1.asmx/GetData",
"type": "POST",
"async" : false,
"contentType": "application/json; charset=utf-8"
}
Now your data will be binded only after the ajax request is completed from your service.
It worked for me.
In your server-side code , use printwriter to send the json data as a string.
PrintWriter out = resp.getWriter();
result.put("iTotalRecords", total);
result.put("iTotalDisplayRecords", totalRecordCount);
result.put("aaData", array);
resp.setContentType("text/jsonp");
out.print(result);
Or else use gson to conver your list of objects to json array
e.g.,
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(dataTableObject);
out.print(json);
NOTE : aaData needs to be set else your data will not be binded.

According to this post option contentType: 'application/json; charset=UTF-8' and type: 'POST' is indeed required to invoke an ASP.NET AJAX web method.
However, in order to send JSON-encoded parameters rather than URL-encoded parameters, you need to use ajax.data option to encode parameters into string in JSON format.
$('#example').dataTable({
"ajax": {
"url": "WebService1.asmx/GetData",
"type": "POST",
"contentType": "application/json; charset=utf-8",
"dataType": "json",
"data": function ( d ) {
return JSON.stringify( d );
},
"dataSrc": "d",
},
"columns": [
{ "data": "Id" },
{ "data": "ActivityID" },
{ "data": "OperationType" },
{ "data": "UserID" },
{ "data": "Comments" },
{ "data": "ActionDate" }
]
});

Related

Add extra column to existing table populated with datatables

I am populating a table with datatables. The table has four columns always. But I need to add another column which can be shown or hidden based on boolean value.
My code so far:
{% show_extra_fields_button = show_extra_fields_bool %}
<table class="display" id="fields_datatable" class="fields_datatable">
<thead>
<tr>
<th>Name</th>
<th>Place</th>
<th>Email</th>
<th>Phone</th>
<th>Add Extra</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="/static/js/vendor/datatables.min.js"></script>
<script>
$(document).ready(function() {
$("#fields_datatable").dataTable({
ajax: {
"processing": true,
"dataSrc": "",
url: 'app/personFields/',
},
"columns": [
{ "data": "name" },
{ "data": "place" },
{ "data": "email" },
{ "data": "phone" },
]
})
if (show_extra_fields_button) {
$("#fields_datatable tr").each(function(){
$(this).append("<td><button>Add Extra</button</td>");
});
}
});
</script>
Here I would want to show the Add Extra column based on the boolean value. I want the header and the column values which will be buttons to be added using js.
How can I do that?
You can use data tables built-in functionality.
To add a button column you can use the following column definition:
{
"data": null,
"name": "buttonColumn",
"render": function (data, type, row) {
return '<button>Add Extra</button>';
}
}
Then use initComplete callback to set the columns' visibility once table has fully been initialised, data loaded and drawn:
$("#fields_datatable").dataTable({
ajax: {
type: "GET",
contentType: "application/json; charset=utf-8",
url: 'app/personFields/',
},
"columns": [
{ "data": "name" },
{ "data": "place" },
{ "data": "email" },
{ "data": "phone" },
{
"data": null,
"name": "buttonColumn",
"render": function (data, type, row) {
return '<button>Add Extra</button>';
}
}
],
"initComplete": function (settings, json) {
// get instance of datatable
table = settings.oInstance.api();
// get column using its name and set visibility
table.column('buttonColumn:name').visible(show_extra_fields_button);
}
});
You can put - instead of deleting that <td> for example <td>-</td>
You can add to the table header just the same way you are adding to the table body.
if (show_extra_fields_button) {
$('#fields_datatable thead tr').append('<th>Add Extra</th>')
}
Execute it just one time.

Invalid JSON format Datatable

I'm trying to implement sever side datatable, but it throws Invalid JSON format error.
CDN
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
HTML
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>EmployeeCode</th>
<th>EmployeeName</th>
<th>ManagerName</th>
<th>DesignationName</th>
</tr>
</thead>
</table>
JS
<script>
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "/api/url",
"columns": [
{ data: "EmployeeCode" },
{ data: "EmployeeName" },
{ data: "ManagerName" },
{ data: "DesignationName" }
],
} );
} );
</script>
JSON
{
"Results":[{"EmployeeCode": "12345"}], // This is just a sample of data
"CurrentPage": 1,
"PageCount": 42,
"PageSize": 10,
"RecordCount": 417
}
it is clear what the issue is, looking at the JSON returned by the XHR/Ajax call to the server. It should just contain the expected data like this:
[
{'EmployeeCode':12345,EmployeeName:'abcde',...},
{'EmployeeCode':12346,EmployeeName:'fghij',...},
...
]
Rather your JSON contains other properties and the data is nested under the "Results" property. Also looking at the documentation, I think you need to format the JSON to contain a data property:
{
"draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
[
"12345",
"John Smith",
"Adam James",
"Manager",
],
...
}
So as a simple fix use the 'dataSrc':'Results' property as suggested by Ankush in your datatable configuration.
Use dataSrc attribute to let datatable know from where to collect data:
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "/api/url",
"dataSrc": function (json) {
debugger;
return json.data;
},
"columns": [
{ data: "EmployeeCode" },
{ data: "EmployeeName" },
{ data: "ManagerName" },
{ data: "DesignationName" }
],
} );
} );
More detail about dataSrc can found here.

import Json to html (table)

im trying to import a json url to html in a table. The problem is when i get the data i get 25 rows i get this on the web console: Object { data: Array[25], paging: Object } I also have the following code which is designed for only one row i guess .And i understand i have Loop over each object, appending a table row with the relevant data of each iteration. The problem is i don´t how to do it, i´m not an expert . Thank you for your help!
This is the data i get on the json url :
{
"data": [
{
"created_time": "2017-11-10T01:24:47+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539014319521507",
"id": "949007375188874_1539014319521507"
},
{
"created_time": "2017-11-10T01:23:37+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539013649521574",
"id": "949007375188874_1539013649521574"
},
{
"created_time": "2017-11-09T23:59:15+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538951229527816",
"id": "949007375188874_1538951229527816",
"shares": {
"count": 20
}
},
{
"created_time": "2017-11-09T23:32:30+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538935439529395",
"id": "949007375188874_1538935439529395"
},
And this my code
<body>
<input type="text" class="txtPagina">
<button class="btnBuscar">Buscar</button>
<table class="tabla" border='1'>
<tr>
<td>created time</td>
<td>permalink url</td>
<td>id</td>
<td>Shares Count</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.btnBuscar').on('click', function (){
var pagina = $('.txtPagina').val();
//Ajax
$.ajax({
type: "GET",
dataType: "json",
url: "https://graph.facebook.com/"+pagina+"/feed?fields=created_time,permalink_url,id,shares& access_token=mytoken",
success: function(data){
console.log(data);
$('.tabla').append("<tr><td>"+data.created_time+"</td><td>"+data.permalink_url+"</td><td>"+data.id+"</td><td>"+data.shares+"</td></tr>");
},
error: function (){
console.log("Error");
}
});
});
});
</script>
</body>
</html>
success: function(data){
console.log(data);
$('.tabla').append("<tr><td>"+data.created_time+"</td><td>"+data.permalink_url+"</td><td>"+data.id+"</td><td>"+data.shares+"</td></tr>");
},
should be
success: function(data){
$.each(data.data, function(i, d){
var s = d.shares ? '<td>'+d.shares.count+'</td>' : '';
$('.tabla').append('<tr><td>'+d.created_time+'</td><td>'+d.permalink_url+'</td><td>'+d.id+'</td>'+s+'</tr>');
});
},
function create(t,attr,parent_node,innerdata){
var dom = document.createElement(t)
for(key in attr){
dom.setAttribute(key,attr[key])
}
dom.innerHTML = innerdata;
parent_node.appendChild(dom)
return dom;
}
window.onload = function () {
var d = {
"data": [
{
"created_time": "2017-11-10T01:24:47+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539014319521507",
"id": "949007375188874_1539014319521507"
},
{
"created_time": "2017-11-10T01:23:37+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539013649521574",
"id": "949007375188874_1539013649521574"
},
{
"created_time": "2017-11-09T23:59:15+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538951229527816",
"id": "949007375188874_1538951229527816",
"shares": {
"count": 20
}
},
{
"created_time": "2017-11-09T23:32:30+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538935439529395",
"id": "949007375188874_1538935439529395"
},
]
}
var tb= document.getElementById('inputTable')
f = {"created_time":1,"permalink_url":1,"id":1,"shares":1}
d['data'].forEach(function(val){
tr_dom = create('tr',{},tb,'')
Object.keys(f).forEach(function(tr){
if(tr in val){
if('shares' == tr)
td_dom = create('td',{},tr_dom,val[tr]['count'])
else
td_dom = create('td',{},tr_dom,val[tr])
}else
td_dom = create('td',{},tr_dom,'')
})
})
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<table border='1'>
<thead>
<th>Create Time</th>
<th>permalink_url</th>
<th>id</th>
<th>Share</th>
</thead>
<tbody id="inputTable">
</tbody>
</table>
</body>
</html>

Zing Feed get data from rest api

I am getting a json data from rest api and i want to use it as input to ZingFeed.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src='http://cdn.zingchart.com/zingchart.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<script>
function getNewData()
{
$.ajax({
type: "GET",
dataType: "json",
headers: {
Accept:"application/json",
"Access-Control-Allow-Origin": "*"
},
url: "/PerformanceMonitor/showProcessUsage/chrome",
success: function(data){
var mem = data.mem.size/10000;
return mem/10000;
//$("#processInfo").append(data.mem.size);
//$("#processInfo").append(" ")
}
});
//return parseInt(memSize);
}
var chartData = {
"type":"line",
"refresh": {
"type": "feed",
"transport": "js",
"url": "feed()",
"interval": 200
},
"series":[
{
"values":[]
}
]
};
window.onload = function() {
zingchart.render({
id: "chartDiv",
data: chartData,
height: 600,
width: "100%"
});
};
window.feed = function(callback) {
var tick = {};
// tick.plot0 = parseInt(10 + 900 * Math.random(), 10);
tick.plot0 = parseInt(getNewData());
//tick.plot0 = parseInt(1);
callback(JSON.stringify(tick));
};
</script>
<div id="processInfo"></div>
<div id='chartDiv'></div>
</body>
</html>
It is working fine when seen in firebug.The data (i.e mem in this case is really huge, so i have divided it twice before assigning it to tick.plot0).
After getting assigned to tick.plot0 .. it shows Nan when hovered over in the developer tools.
Could you help me plotting these huge values in ZingFeed Charts
Thanks in advance
The issue here is the nature of asynchronous functions in Javascript. Returning the data from AJAX doesn't work the way you've attempted above. You can read more about it here.
Here's a working solution.
I work on the ZingChart team. Let me know if you have other questions about the ZingChart library.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src='http://cdn.zingchart.com/zingchart.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<script>
var chartData = {
"type":"line",
"refresh": {
"type": "feed",
"transport": "js",
"url": "feed()",
"interval": 200
},
"series":[
{
"values":[]
}
]
};
window.onload = function() {
zingchart.render({
id: "chartDiv",
data: chartData,
height: 600,
width: "100%"
});
};
window.feed = function(callback) {
$.ajax({
type: "GET",
dataType: "json",
headers: {
Accept: "application/json",
"Access-Control-Allow-Origin": "*"
},
url: "/PerformanceMonitor/showProcessUsage/chrome",
success: function (data) {
var mem = data.mem.size/10000;
var tick = {
plot0: parseInt(mem)
};
callback(JSON.stringify(tick));
}
});
};
</script>
<div id="processInfo"></div>
<div id='chartDiv'></div>
</body>

Create table if data from ajax not empty

First I have HTML:
<div class="showTable" style="display: none;">
<table id="example" class="table table-responsitive" cellspacing="0" width="100%" style="margin-top:30px;">
<thead>
<tr>
<th>ID</th>
<th>Broj računa</th>
<th>Kupac</th>
<th>Datum izdavanja</th>
<th>Rok za plaćanje</th>
<th>Status</th>
<th></th>
</tr>
</thead>
</table>
</div>
<div class="showInfo" style="display: none">
</div>
After that I write JS:
$(document).ready(function() {
drawVisualization();
});
function drawVisualization() {
console.log('proba');
$.ajax({
url: "getracuni.php",
type: "POST",
async: true,
dataType: "html",
success: function(json) {
console.log(json);
if (!json.data){
json.data = [];
$('.showInfo').show();
} else {
var podaci = json.data;
$('.showTable').show();
showTable(podaci);
}
},
error: function(data) {
console.log(data);
}
});
};
so here I try to make this:
1. IF data from ajax is not empty then to create datatable with function showTable(podaci);
2. IF data from ajax is empty then just want to show div class 'showInfo'.
My showTable(podaci) function is:
function showTable(podaci) {
$('#example').dataTable({
data: podaci.data,
paging: false,
"dom":' <"search"f><"top"l>rt<"bottom"ip><"clear">',
bfilter: false,
"oLanguage": {
"sInfo": 'Ukupno _END_ računa.',
"sInfoEmpty": 'Nema podataka o računima',
"sEmptyTable": "Nemate račune, dodajte klikom na dugme ispod.",
},
// end ,
"columns": [{
"data": "ID"
}, {
"data": "br"
},
{
"data": "kupac"
},
{
"data": "datum"
},
{
"data": "rok"
},
{
"data": "status"
},
{
"data": "akcija"
}
],
"columnDefs": [
{
"targets": 6,
"data": "akcija",
"render": function(data, type, full, meta) {
// return data;
return '<div style="float:right;"><div class="btn-group">Izmeni <span class="caret"></span><ul class="dropdown-menu"><li>Izmeni</li><li>Pošalji</li><li>Opomeni</li><li>Plaćeno</li><li>Stoniraj</li><li>Kopiraj</li><li>Obriši</li></ul></div> <i data-toggle="modal" data-target="#delete" class="fa fa-times"></i></div>';
}
},
{
"targets": 0,
"visible":false
}
]
});
}
Also I get data from ajax in this JSON format:
{"data":[{"ID":1,"br":"1-2015","kupac":"ADAkolor","datum":"2015-05-19","rok":"2015-05-21","status":"placeno"},{"ID":2,"br":"2-2015","kupac":"Milenk","datum":"2015-05-27","rok":"2015-05-28","status":""}]}
I think that I write everything fine but when I try to run this code I just get blank screen. SO anything wont to show there...
Change your condition
if (!json.data) to if (json.data!=null)

Categories