Trying to insert JSON data into a datatable widget - javascript

I have a Java Web Project where I have a GET endpoint that I am hitting to retrieve JSON data. Firebug shows I am getting the JSON data in the form
[{"id":7,"serial":"7bc530","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":8,"serial":"4a18d27","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":9,"serial":"f30ef","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":10,"serial":"9e6d","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":11,"serial":"4d8665a3","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null},
{"id":12,"serial":"4fe1457","randomDouble":0.0,"randomDouble2":0.0,"randomDouble3":0.0,"date":1352228474000,"removed":null}]
On the HTML side I have this,
<table id="table_id">
<thead>
<tr>
<th>id</th>
<th>serial</th>
<th>randomDouble</th>
<th>randomDouble2</th>
<th>randomDouble3</th>
<th>date</th>
<th>removed</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here is what I have on the javascript side, I found another post from someone on here with this format that worked for them.
$(document).ready(function() {
var Table = $("#table_id").dataTable({
"bFilter":false,
"bPaginate":false,
"bProcessing": true,
"bServerSide":true,
"bInfo":false,
"sAjaxSource": ApiUrl(),
"fnServerData": function (sSource, aoData, fnCallback){
$.ajax({
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"success": fnCallback
});
}
});
The table is displaying the columns, but it isn't pulling in the data. As I said, I did verify that the JSON data is getting sent to the webpage through Firebug -- through the GET request this is making.
I find datatables to be extremely confusing and I can't get this JSON to actually populate...
Any assistance would be very appreciated.
Edit:
I tried this,
var Table = $("#table_id").dataTable({
"bFilter":false,
"bPaginate":false,
"bProcessing": true,
"bServerSide":true,
"bInfo":false,
"sAjaxSource": ApiUrl(),
"sAjaxDataProp": ""
});

This should work for server side:
var Table = $("#table_id").dataTable({
"bFilter":false,
"bPaginate":false,
"bProcessing": true,
"bServerSide":true,
"bInfo":false,
"aoColumns": [
{ "mData": "id" },
{ "mData": "serial" },
{ "mData": "randomDouble" },
{ "mData": "randomDouble2" },
{ "mData": "randomDouble3" },
{ "mData": "date" },
{ "mData": "removed" }
],
"sAjaxSource": "url",
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.getJSON( sSource, aoData, function (json) {
map = {}
map["aaData"] = json
fnCallback(map)
} );
}
});
UPDATE regarding last comment:
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.getJSON( sSource, aoData, function (json) {
$.getJSON('second_json_url', function(secondjson) {
$.each(secondjson, function(index, object) {
json[index].serial = secondjson[index].name
})
map = {}
map["aaData"] = json
fnCallback(map)
})
});
}

You can read from an arbitrary data source. Check out the documentation below (found here). This works for server-side processing and ajax data sources.
Additionally, it is possible to set sAjaxDataProp to be an empty
string, which results in DataTables treating the given data source as
the table data array (rather than as property of an object).

Related

View Source: JSON Response is showing instead of HTML source code

So, when I view my page source, the json response (aka the table i'm retrieving) is showed instead of the html page.
I've been trying to figure out at first how to retrieve a json response while still rendering the HTML, which had me to come up with this controller code. Would like to help on how to improve my code to solve this problem. Would appreciate suggestions!
My controller:
$products = Product::all();
if (\Illuminate\Support\Facades\Request::ajax())
return response()->json($products);
else
return view('products.index');
Jquery Script:
$(document).ready( function () {
var pathname = window.location.pathname;
loadProducts();
function loadProducts(){
var columns = [{
"sTitle": "Name",
"mData": "name"
}, {
"sTitle": "Price",
"mData": "price"
}, {
"sTitle": "Category_ID",
"mData": "category_id"
}, {
"sTitle": "Supplier_ID",
"mData": "supplier_id"
}]
$.ajax({
'url': '{{ url('products') }}',
'method': "GET",
'contentType': 'application/json'
}).done( function(data) {
var example_table = $('#myTable').DataTable({
"aaData": data,
"columns": columns
});
});
}
I suggest you use DataTable JSONP data source for remote domains
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "scripts/jsonp.php",
"dataType": "jsonp"
}
} );
} );

Populate datatable with custom nested response

I am very new to data tables. And I need to populate data table with custom response other than default data table response.
please see this fiddle. It is working fine with simple response , BUT now I need to populate data table with more complex response. Below is my code.
HTML
<table id="table" class="display responsive nowrap" cellspacing="0" width="100%">
<thead style="background-color:#303641;color:#fff;">
<tr>
<th>id</th>
<th>number</th>
<th>maxDate</th>
<th>minDate</th>
<th>number2</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JAVASCRIPT
$(document).ready(function() {
var result = '{"msg":"success","code":"200","status":null,"data":[{"id":3663101,"lstImeis":[{"number":"18966399926043","maxDate":"2017-08-24 22:08:58.0","minDate":"2017-08-24 22:08:58.0"},{"number":"22418344742097","maxDate":"2017-08-24 18:08:56.0","minDate":"2017-08-24 18:08:56.0"}],"number2":789},{"id":3665337,"lstImeis":[{"number":"32756451080799","maxDate":"2017-08-24 21:09:38.0","minDate":"2017-08-24 21:09:38.0"},{"number":"42540009239622","maxDate":"2017-08-24 16:35:08.0","minDate":"2017-08-24 16:35:08.0"}],"number2":456}],"draw":0,"limit":0,"recordsFiltered":0,"recordsTotal":0}';
var json = JSON.parse(result);
var tableData = json.data;
$('#table').DataTable({
"processing": true,
"serverSide": false,
"bFilter": false,
"aaData": tableData,
"aoColumns": [{
"mData": "id"
}, {
"mData": "number"
}, {
"mData": "maxDate"
}, {
"mData": "minDate"
}, {
"mData": "number2"
}]
});
});
With this JSON response, I am unable to populate the required data in data table. I have created this fiddle as well.
I have studied this link as well, but I dopnt understand how to manage nested response in data table.
Any idea, how to populate this data into data table. ? OR any good reference ?
OK, so after some help from google, I manage to show the correct response, I used the follwoiung java script code to populate my data into data table.
$(document).ready(function () {
var result = '{"msg":"success","code":"200","status":null,"data":[{"id":3663101,"lstImeis":[{"number":"18966399926043","maxDate":"2017-08-24 22:08:58.0","minDate":"2017-08-24 22:08:58.0"},{"number":"22418344742097","maxDate":"2017-08-24 18:08:56.0","minDate":"2017-08-24 18:08:56.0"}],"number2":789},{"id":3665337,"lstImeis":[{"number":"32756451080799","maxDate":"2017-08-24 21:09:38.0","minDate":"2017-08-24 21:09:38.0"},{"number":"42540009239622","maxDate":"2017-08-24 16:35:08.0","minDate":"2017-08-24 16:35:08.0"}],"number2":456}],"draw":0,"limit":0,"recordsFiltered":0,"recordsTotal":0}';
var json = JSON.parse(result);
var tableData = json.data;
$('#table').DataTable({
"processing": true,
"serverSide": false,
"bFilter": false,
"aaData": tableData,
"aoColumns": [
{ "mData": "id" },
{ "mData": "lstImeis.0.number" },
{ "mData": "lstImeis.0.maxDate" },
{ "mData": "lstImeis.0.minDate" },
{ "mData": "number2" }
],
});
});
I hope it will help some one else !!

How to use datatables in ajax

I want to try pagination using datatables.net via ajax.
I have 2 input fields which sends start date and end date and following is the table structure
<table class="table table-hover" id="example">
<thead>
<tr>
<th>Loan ID</th>
<th>Date</th>
<th>Loan Amount</th>
<th>Loan Type</th>
</tr>
</thead>
<tbody id="amount"></tbody></table>
when the button is clicked,I am calling this function
$('#recv').click(function(){
var fromDate=$('#from').val();
var toDate=$('#to').val();
var test=$.ajax({
type: "GET",
url: "/project/getDetails",
data:{"fromDate":fromDate,"toDate":toDate},
dataType:"json",async:false
}).responseText;
var result = eval('('+test+')');
$('#example').dataTable( {
"bServerSide": true,
"sAjaxSource": result,
"bProcessing": true,
"aoColumns": [
{ "sName": "Loan_ID",
"bSearchable": false,
"bSortable": false
},
{ "sName": "Date" },
{ "sName": "Loan_Amount" },
{ "sName": "Loan_Type" }
]
} );
When Ever I click on the button then I get error in alert box saying datatables warning id=example ajax error
Can anybody please tell me how to solve?
Let datatables take care of the ajax call:
var oTable = $('#example').dataTable( {
"bServerSide": true,
"iDeferLoading": 1,
"sAjaxSource": "/project/getDetails",
"fnServerParams": function (aoData) {
aoData.push({ "name": "fromDate", "value": $('#from').val() });
aoData.push({ "name": "toDate", "value": $('#to').val() });
},
"bProcessing": true,
"aoColumns": [
{ "sName": "Loan_ID",
"bSearchable": false,
"bSortable": false
},
{ "sName": "Date" },
{ "sName": "Loan_Amount" },
{ "sName": "Loan_Type" }
]
} );
$('#recv').click(function(){
oTable.fnDraw();
});
Points to note:
fnServerParams this passes your start & end date to the
getDetails function
iDeferLoading - prevent table population on page load
fnDraw() populates the datatable from your click event

JS dataTable plugin: handling json format other than standard datatable format

I am new to Datatables and trying to figure out this problem.
I have a server which oupts json in certain format(see below).I cant change that on server side.
**Note: I am using link http://www.json-generator.com/j/cftupHnpbC?indent=4 to emulate my server response just for checking.
I have 2 problems
Since My json response doesn't have aaData: thing required by dataTable, I cant seem to initiliaze it.
Even if I add aaData: by hand to json just for checking, dataTable cant count total records.How I can set that manually ?Since I cant change output from server.
JSBIN LINK:
http://live.datatables.net/dasuyaf/1/edit
HTML:
<table id="example" class="display" width="100%">
<thead>
<tr>
<th> </th>
<th>ID</th>
<th>Name</th>
<th>Text</th>
</tr>
</thead>
<tbody></tbody>
</table>
JS:
$(document).ready( function () {
var table = $('#example').dataTable({
"sAjaxSource": "http://www.json-generator.com/j/cftupHnpbC?indent=4",
"aoColumns": [{
"mData": "id",
"mRender": function (data, type, full) {
return '<input type="checkbox" name="chkids[]" value="' + data + '">';
}
}, {
"mData": "id"
}, {
"mData": "name"
}, {
"mData": "text"
}],
"bProcessing": true,
"bServerSide": true,
"sServerMethod": "GET",
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}],
"fnDrawCallback": function (oSettings) {
console.log(this.fnSettings().fnRecordsTotal());
}
});
});
My Server Output: (cant change this)
[
{
"text": "Some text",
"name": "somedata",
"id": "89"
},
{
"text": "Some text",
"name": "somedata",
"id": "2"
},
{
"text": "Some text",
"name": "somedata",
"id": "12"
}
]
I suppose you could just request that JSON yourself, make an object out of it and pass it to your dataTable.
var aaData;
var table;
$(document).ready( function () {
$.ajax({
url: 'http://www.json-generator.com/j/cftupHnpbC?indent=4'
}).done(function(data){
aaData = data;
table = $('#example').dataTable({
"aaData": aaData,
"aoColumns": [{
"mData": "id",
"mRender": function (data, type, full) {
return '<input type="checkbox" name="chkids[]" value="' + data + '">';
}
}, {
"mData": "id"
}, {
"mData": "name"
}, {
"mData": "text"
}],
"bProcessing": true,
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [0]
}],
"fnDrawCallback": function (oSettings) {
console.log(this.fnSettings().fnRecordsTotal());
}
});
});
} );
I removed bServerSide - I don't think there's any way you can make use of it if you can't change your server response. Also removed sServerMethod.

Datatables with serverside JSON (custom object)

I am trying to quickly create a simple display of results from an internal API using DataTables. The API returns JSON in the following structure:
obj {
status: 1,
results: 100,
offset: 25,
limit: 25,
data: [
[1]: {
title: "Blah blah one",
description: "Doesn't really matter",
misc: "Yadda yadda"
},
[2]: {
title: "Blah blah two",
description: "Doesn't really matter",
misc: "Yadda yadda"
},
]
}
I can't/don't want to change the API structure just because DataTables uses a weird structure, but I would like to access the built in functionalities for paging, dynamic loading, etc. DataTables seems to allow for custom data objects, and I've gotten the table to load with the following:
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "http://api.oursite.com/api?limit=100",
"fnServerData": function( sUrl, aoData, fnCallback, oSettings ) {
oSettings.jqXHR = $.ajax( {
"url": sUrl,
"data": aoData,
"success": fnCallback,
"dataType": "jsonp",
"cache": false
} );
},
"sAjaxDataProp": "data",
"aoColumns": [
{ "mData": "title" },
{ "mData": "description" },
{ "mData": "misc" },
]
} );
});
But, none of the paging or sorting functions work. I think this is because DataTables requires a results count and paging variable in the object— "iTotalRecords" and "iTotalDisplayRecords". Is this correct? Is there any way to use the api variables instead? Thanks in advance. I'm currently not getting any errors in the dev console, so if it's erroring it's doing so silently...
While initializing the datatable, instead of directly assigning source to Ajaxsource, you can set the aaData to the javascript function where you can manipulate to return only obj.data. You need handle few things manually.
$('#tblExample').dataTable({
"bJqueryUI": true,
"bDestroy":true,
"bSortable": false,
"sAjaxSource": "",
"aaData":GetData(),
"aoColumns": [
{
"sTitle":"Index","mDataProp": null, "sWidth": "20px", "sDefaultContent": "<span class='ui-icon ui-icon-circle-close' onclick='RemoveActiveItem(this);'></span>", "bSortable": false},
{ "mDataProp": "Year"},
{ "mDataProp": "Month"},
{ "mDataProp": "Savings"}
]
});

Categories