why won't jquery datatable populate? - javascript

This is driving me nuts. I have a web site that works fine. Datatable populates from a .php ajax call. I'm migrating that code to a different web site. Identical ajax call but this time won't populate!
Here is the js of the one that works:
$('#divTable').DataTable({
"ajax": "screen_highYield.php",
"columns": [
{ "data": "Symbol" },
{ "data": "CompanyName" },
{ "data": "ExDivDate" },
{ "data": "Dividend" },
{ "data": "DivYield" },
{ "data": "DivFrequency" },
{ "data": "DivPayDate" }
]
});
And the html:
<div id="highYieldDiv">
<table id="divTable" class="display" style="width:100%">
<thead>
<tr>
<th>Symbol</th>
<th>Company Name</th>
<th>Ex-Div<br>Date</th>
<th>Dividend</th>
<th>Div<br>Yield%</th>
<th>Div<br>Frequency</th>
<th>Pay Date</th>
</tr>
</thead>
</table>
</div>
Here is the js of the one that fails:
$('#divTable').DataTable({
"ajax": {
url: "screen_highYield.php",
"done": function() {
alert('done');
},
"success": function(data) {
console.log(JSON.stringify(data));
},
"error": function(jqXHR, textStatus, errorThrown) {
alert('error');
},
"initComplete": function(settings, json) {
alert( 'DataTables has finished its initialisation.' );
}
},
"columns": [
{ "data": "Symbol" },
{ "data": "CompanyName" },
{ "data": "ExDivDate" },
{ "data": "Dividend" },
{ "data": "DivYield" },
{ "data": "DivFrequency" },
{ "data": "DivPayDate" }
]
});
And the html:
<div id="highYieldDiv">
<table id="divTable" class="display" style="width:100%">
<thead>
<tr>
<th>Symbol</th>
<th>Company Name</th>
<th>Ex-Div<br>Date</th>
<th>Dividend</th>
<th>Div<br>Yield%</th>
<th>Div<br>Frequency</th>
<th>Pay Date</th>
</tr>
</thead>
</table>
</div>
I added the "done", "success", "error", and "initComplete" in an attempt to figure out what's wrong. Nothing was output to the console. Then I moved the js to the $(document).ready function and then I got the "success" to trigger. (Didn't have to do that in the one that works.) I took the json it output and verified it was valid json using jsonlint. The table just says Loading...
I don't understand why it works one place an not another. These black boxes are so mysterious and difficult to debug. Ideas?

Related

Data tables not responding to provided json result from api call to fill table with data

This is the JSON result being return from the API call.
{
"LoanOfficers": [{
"Id": 13,
"FirstName": "Smith",
"LastName": "Kerry",
"EmailAddress": "kerry.smith#test.com",
"LoanOfficerUrlParameterId": 312,
"UrlParameter": "/smithkerry123"
}, {
"Id": 713,
"FirstName": "Kerry",
"LastName": "Smith",
"EmailAddress": "kerry.smith#test.com",
"LoanOfficerUrlParameterId": 654,
"UrlParameter": "/kerrysmith1234578"
}]
}
I implemented the data table below. The call works and fetches the data and puts it into an object. From there the table reads no data in the table. I use a console.log() to see if the data was being passed back but it is but I don't know why it's not returning to the datable.
$(document).ready(function () {
$.ajax({
url: '/CallAPI',
type: 'GET',
dataType: 'json',
success: function (data) {
assignToEventsColumns(data);
}
});
function assignToEventsColumns(data) {
console.log(data);
var table = $('#table_id').dataTable({
"bAutoWidth": false,
"aaData": data,
"columns": [
{ "data": "Id" },
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "EmailAddress" },
{ "data": "LoanOfficerUrlParameterId" },
{ "data": "UrlParameter" }
],
"order": [[1, 'asc']]
})
}
});
Console log of the JSON object return from API call
I am new to data tables with JSON data don't understand fully understand why this issue is occurring. Any explanation would be much appreciated. All is I know that is returning a valid JSON format because I already tested that. I provided as much detail as possible. I provided an example of the JSON result and an example of console.log.
HTML
<table class="dataTable table table-striped text-center table-hover" id="table_id">
<thead>
<tr class="bg-green">
<th>Loan Officer ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>LoanOfficerUrlParameterId</th>
<th>Url</th>
#*<th></th>*#
</tr>
</thead>
<tfoot>
<tr class="bg-green">
<th>Loan Officer ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>LoanOfficerUrlParameterId</th>
<th>Url</th>
#*<th></th>*#
</tr>
</tfoot>
</table>

Datatables.net json data load

I am trying to load the below json data into Datatables, but I'm facing error. My web browser(chrome) successfully downloads the data, but it does not represent the data. The table shows only the name of columns but nothing. Can someone please help me?
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"Feature_ID": "4",
"Clean_Feature_Name": "Abalos Colles",
"Feature_Type": "Collis, colles",
"Feature_Type_Code": "CO",
"title": "['Arecibo radar imagery of Mars: II. Chryse-Xanthe, polar caps, and other regions']",
"author": "['Harmon, John K.', 'Nolan, Michael C.']",
"year": 2017,
"bibcode": "2017Icar..281..162H",
"pub": "Icarus"
}
}
]
}
And below is my javascript code.
$(document).ready(function() {
$('#example').DataTable( {
"ajax" : {
"url" : "http://212.201.46.76/data_final/sample_paper.json",
},
"columns" : [
{ "features" : "properties.Feature_Id" },
{ "features" : "properties.Clean_Feature_Name" },
{ "features" : "properties.Feature_Type" },
{ "features" : "properties.Feature_Type_Code" },
{ "features" : "properties.title" },
{ "features" : "properties.author" },
{ "features" : "properties.year" },
{ "features" : "properties.bibcode" },
{ "features" : "properties.pub" },
]
} );
} );
My HTML code
<body>
<button id="reload">Reload</button>
<div class="container">
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>Feature_ID</th>
<th>Clean_Feature_Name</th>
<th>Feature_Type</th>
<th>Feature_Type_Code</th>
<th>Bibcode</th>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Pub</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Feature_ID</th>
<th>Clean_Feature_Name</th>
<th>Feature_Type</th>
<th>Feature_Type_Code</th>
<th>Bibcode</th>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Pub</th>
</tr>
</tfoot>
</table>
</div>
</body>
You're specifying your columns array wrong.
The columns array is where you specify a number of options in your table, on a per-column basis. There is no features option available; presumably that's why you're not seeing a table. Available values are here.
Now, you should be able to simply do this:
$(document).ready(function() {
$('#example').DataTable( {
"ajax" : {
"url" : "http://212.201.46.76/data_final/sample_paper.json",
}
});
});
as in this example (which you probably used to get started), removing your columns definition entirely. You've already specified the columns using HTML. If you need different options from the example, you need to learn to use columns correctly.
For more information on this, see this post.
Finally I found a solution.
This is how you do when the json file has different format with examples.
"dataSrc" <-- follow your json format
{ "data" : "properties.title"} <-- "data" is always "data' it's a fixed key. you should not change it whatever "dataSrc" is.
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"ajax" : {
"url": "http://212.201.46.76/data_final/sample_paper.json",
"dataSrc": "features"
},
"columns": [
{ "data" : "properties.title" },
{ "data" : "properties.author" },
{ "data" : "properties.year" },
{ "data" : "properties.bibcode" },
{ "data" : "properties.pub" }
]
});

representing Json Object data on a DataTable is not working for me

I am working on a java web application (Spring Frame work). Once a certain URL is hit, a Json object is created. I have access to this data and I was able to console.log it. But I need to display this Json object which is an array of more than 1000 of record in a table format. The thing that I am not sure is how to do it. I have used this tutorial(https://datatables.net/examples/ajax/null_data_source.html), to do some thing but I was not successful. I am very new at this concept and my question might be really dump. But I was wondering maybe I can get some help from here.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
>
<h:head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src ="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="resource/css/jquery.dataTables.min.css"></link>
</h:head>
<h:body>
<button id="processData">ProcessData</button>
<div id="wrapper">
<div id="header">
<h2>List of processed data</h2>
</div>
</div>
<table id="dataTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID1</th>
<th>ID2</th>
<th>Number Of Matching Terms</th>
<th>Matching Terms </th>
<th>Original Terms in Data Source One</th>
<th>Original Terms in Data Source Two</th>
<th>Acceptance Action</th>
<th>Decline Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID1</th>
<th>ID2</th>
<th>Number Of Matching Terms</th>
<th>Matching Terms </th>
<th>Original Terms in Data Source One</th>
<th>Original Terms in Data Source Two</th>
<th>Acceptance Action</th>
<th>Decline Action</th>
</tr>
</tfoot>
</table>
<script src="js/mainJs.js"></script>
</h:body>
here is my js code:
$(document).ready(function(){
$("#processData").click(function (){
$.getJSON('http://localhost:8080/gtlc/PVJson', function(data){
console.log(data);
});
var table = $('#dataTable').DataTable( {
"ajax": data,
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
});
})
});
</html>
when I look at my console I can see the following:
here is the error I get
Here is a small sample of my json object
"records": [{
"id1": 1200314690100003429,
"id2": 1045,
"matchingTerms": ["adaptor"],
"orginalTermsTable1": ["AC ADAPTOR FOR JDE", "www.greenlightcorp.net", "AC ADAPTOR FOR JDE", ""],
"orginalTermsTable2": ["Greenlight Technologies, Inc.", "GRC Adaptor for People Soft", "Customized software for SAP, therefore version not specified"]
}, {
"id1": 1200314690100003429,
"id2": 1046,
"matchingTerms": ["adaptor"],
"orginalTermsTable1": ["AC ADAPTOR FOR JDE", "www.greenlightcorp.net", "AC ADAPTOR FOR JDE", ""],
"orginalTermsTable2": ["Greenlight Technologies, Inc.", "GRC Adaptor for Oracle", "Customized software for SAP, therefore version not specified"]
}]
I was wondering if some one could give me some hints on how I can get a hold to the json object and represent it on the dataTable
The problem is that the DataTable is being initialized a microsecond after ajax request.
When the Ajax request is sent, it might take 1, 2, 3 or 10 seconds to come back with the data... so data is undefined until the Ajax response comes back.
Move your DataTable initialization in the callback function at it should work.
FIDDLE
$(document).ready(function() {
var data = {
"records": [{
"id1": 1200314690100003429,
"id2": 1045,
"matchingTerms": ["adaptor"],
"orginalTermsTable1": ["AC ADAPTOR FOR JDE", "www.greenlightcorp.net", "AC ADAPTOR FOR JDE", ""],
"orginalTermsTable2": ["Greenlight Technologies, Inc.", "GRC Adaptor for People Soft", "Customized software for SAP, therefore version not specified"]
}, {
"id1": 1200314690100003429,
"id2": 1046,
"matchingTerms": ["adaptor"],
"orginalTermsTable1": ["AC ADAPTOR FOR JDE", "www.greenlightcorp.net", "AC ADAPTOR FOR JDE", ""],
"orginalTermsTable2": ["Greenlight Technologies, Inc.", "GRC Adaptor for Oracle", "Customized software for SAP, therefore version not specified"]
}]
};
var table = $('#dataTable').DataTable({
"data": data.records,
"columns": [{
"data": "id1"
},
{
"data": "id2"
},
{
"data": "matchingTerms",
"render": function(data, type, row, meta) {
return data.length;
}
},
{
"data": "matchingTerms"
},
{
"data": "orginalTermsTable1"
},
{
"data": "orginalTermsTable2"
},
{
"data": "",
"render": function(data, type, row, meta) {
return "<button>Click</button>";
}
},
{
"data": "",
"render": function(data, type, row, meta) {
return "<button>Click</button>";
}
}
]
});
});
Better solution :
FIDDLE
$(document).ready(function() {
var table = $('#dataTable').DataTable({
"ajax": {
"url" : "http://localhost:8080/gtlc/PVJson",
"dataSrc" : "records"
},
"columns": [{
"data": "id1"
},
{
"data": "id2"
},
{
"data": "matchingTerms",
"render": function(data, type, row, meta) {
return data.length;
}
},
{
"data": "matchingTerms"
},
{
"data": "orginalTermsTable1"
},
{
"data": "orginalTermsTable2"
},
{
"data": "",
"render": function(data, type, row, meta) {
return "<button>Click</button>";
}
},
{
"data": "",
"render": function(data, type, row, meta) {
return "<button>Click</button>";
}
}
]
});
});

Bootstrap dataTable search and pagination is not working when data is loading from ajax API response

I developing a admin panel. I am able to load data that is getting from Ajax API response in bootstrap dataTable but default search and pagination of the table is not working.
I tried
"processing": true,
"serverSide": true
to initialize the table but it is not working.
Is It possible this dataTable functionality work as default provided by the Bootstrap dataTable.
I want to achieve the following steps:
Step1: A form with submit button.
Step2: When clicked on submit, make an ajax call and get JSON Data back to add it into dataTable rows dynamically.
Step3:
$("#editable-sample").DataTable({ // what should I do here.});
Problem
Data is loading but search box and pagination is not woking on the page.
Can you post your code?
Are you sure you fulfilled the dataTables prerequisites:
The table must have <thead> and <tbody> tags
The table must have an id that is used in the launch script example:
<table class="table table-bordered" id="dataTables-example">
<script>
$(document).ready(function() {
$('#dataTables-example').dataTable();
});
</script>
datatables supports Ajax data source (objects), see
Below you can see an example which taken from dataTables' doc
JS
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "data/objects.txt", //
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
} );
} );
HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
AJAX
{
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"name": "Donna Snider",
"position": "Customer Support",
"salary": "$112,000",
"start_date": "2011/01/25",
"office": "New York",
"extn": "4226"
}
]
}
$.ajax({..
success: function(data) {..
var table = $('#datatable').DataTable();
table.clear().draw();
var rowNode= new Array();
for (var key=0, size=data.length; key<size; key++){
var j = -1;
var r = new Array();
// represent columns as array
r[++j] ='<tr><td><input type="hidden" name="somename1" value="'+data[key].id+'"/><input type="hidden" name="somename2" value="'+data[key].is_deleted+'"/>'+data[key].lic_category_name+'</td>';
r[++j] = '<td>'+data[key].someval1+'</td>';
r[++j] = '<td>'+ data[key].someval2+'</td>';
r[++j] = '<td>'+ data[key].someval13+ '</td>';
r[++j] ='<td class="last"><i class="fa fa-eye"></i> <i class="fa fa-edit"></i> <i class="fa fa-trash"></i></td></tr>';
rowNode = table.row.add(r);
}
rowNode.draw().node()
}
}
My JSON Response,
[{"id":70,"somekey1":"GC 1","somekey2":"GC 1","somekey3":8,"somekey4":5000,"somekey5":1,"somekey5":1,"is_deleted":0}]
It worked for me ..
The problem occurred because of 'column' attribute try to match data row values with column before it get the data.
so i place the close Curly bracket of 'ajax' attribute before 'column' attribute.
now the column attribute function get call only after ajax function is complete.
$(document).ready(function() {
$('#example').DataTable( {
"ajax":{ "data/objects.txt" },//<------------------------------------------------place here//
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
});
} );

DataTables - Uncaught TypeError: Cannot read property 'length' of undefined

I've seen several examples of this problem but still haven't been able to find a resolution.
The error says it breaks on jquery.dataTables.js (version 1.10.4) on line 3287 shown below
// Got the data - add it to the table
for ( i=0 ; i<aData.length ; i++ ) {
_fnAddData( settings, aData[i] );
}
This is my controller. The controller is this way because the the lack of db connection right now, but will have JSON returned in the same format as $data. I have tried several things to resolve the error, but keep running into other issues. The JSON IS valid.
public function test()
{
$data = '{"persons": [{"branch": "CORP","phone_numbers": [{"desk": "5223422117"},{"mobile": "5022319224"},{"branch": "422-922-2291"}],"email": "twilliams#test.com","preferred_name": "Thomas","person_id": 368,"department": "IT","first_name": "Thomas","title": "Programming Manager","last_name": "Williams"}]}';
$data = json_encode($data);
echo $data;
}
My javascript
$(document).ready(function() {
$('#directory_table').dataTable( {
"ajax": {
"url": "test",
"type": "JSON"
},
"aoColumns": [
{ "persons": "preferred_name" },
{ "persons": "last_name" },
{ "persons": "phone_numbers.0" },
{ "persons": "phone_numbers.1" },
{ "persons": "phone_numbers.2" },
{ "persons": "email" },
{ "persons": "department" },
{ "persons": "title" }
]
} );
} );
My HTML
<table id='directory_table' class="display">
<thead>
<tr style='background: #186A9F; color: white;'>
<th>First Name </th>
<th>Last Name</th>
<th>Desk Number</th>
<th>Mobile</th>
<th>Branch</th>
<th>Email</th>
<th>Department</th>
<th>Title</th>
</tr>
<thead>
</table>
CAUSE
By default DataTables expects JSON response to have certain structure, see documentation.
Array of arrays:
{
"data": [
[ "value1", "value2" ],
...
]
}
Array of objects:
{
"data": [
{
"attr1": "value1",
"attr2": "value2"
},
...
]
}
Error occurs because name of the data property in your response holding array of objects (persons) differs from default (data).
SOLUTION
Use ajax.dataSrc option to define the property from the data source object (i.e. that returned by the Ajax request) to read.
$('#directory_table').dataTable( {
"ajax": {
"url": "test",
"dataSrc": "persons"
},
"columns": [
{ "data": "preferred_name" },
{ "data": "last_name" },
{ "data": "phone_numbers.0.desk" },
{ "data": "phone_numbers.1.mobile" },
{ "data": "phone_numbers.2.branch" },
{ "data": "email" },
{ "data": "department" },
{ "data": "title" }
]
});
Alternatively if you can change data property name in JSON response from persons to data, then adding "dataSrc": "persons" wouldn't be needed.
DEMO
See this jsFiddle for code and demonstration.
LINKS
See jQuery DataTables: Common JavaScript console errors for more information on this and other common console errors.

Categories

Resources