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"}
]
});
Related
I thought to be a simple thing, but!
Using DataTables, I would like to have the first column of the table hidden and use that cell data in an HTML image link in the next column cell.
html link using "User_ID", http://somepage.php?UID=data0
I have looked at fnGetData() and mRender and I just confused now.
MY CODE:
"aoColumns": [
{ "mData": "User_ID",
"bVisible": false, "bSearchable": false, "bSortable": false
},
{ "mData": null,
"bSearchable": false, "bSortable": false,
"sClass": "center",
"sDefaultContent": '<img src="images/look.png" width="16">'
},
I always help myself with this trick:
Don't set bVisible to false cause you will not have the data in the row. It's not rendered at all. Use sClass and set display:none. This way the column is invisible to the user, but it is still there.
Then you can use mRender to show a custom cell template:
"aoColumnDefs": [{
"aTargets": [0],
"sClass": "hiddenID"
}, {
"aTargets": [1],
"bSearchable": false,
"bSortable": false,
"sClass": "center",
"mRender": function(data, type, full) {
return 'Click me';
}
}, {
"aTargets": [2],
}, ]
Now the data is there, sortable and filterable.
Look at this Plunker and style.css to understand the concept behind this hack.
You may have a closer look at mData so you can do a callback function and dont have to use the hidden column:
// Using mData as a function to provide different information for
// sorting, filtering and display.
$(document).ready( function() {
var oTable = $('#example').dataTable( {
"aoColumns": [
{ "mData": "User_ID",
"bVisible": true, "bSearchable": false, "bSortable": false
}
],
"aoColumnDefs": [ {
"aTargets": [ 0 ],
"mData": function ( source, type, val ) {
if (type === 'set') {
source.id = val;
// Store the computed dislay and filter values for efficiency
source.id_display = val=="" ? "" : '<img src="images/look.png" width="16">';
source.id_filter = val=="" ? "" : val;
return;
}
else if (type === 'display') {
return source.id_display;
}
else if (type === 'filter') {
return source.id_filter;
}
// 'sort', 'type' and undefined all just use the integer
return source.id;
}
} ]
} );
} );
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.
i am newbie in web programming and datatables and i am trying to add new data to my tables using fnAddData() but it not work
here is my code
$('#btn_ubahbj').click( function() {
//inisialisasi table upproses
Otableupproses=$('#tableupproses').dataTable( {
'sDom': 't',
"bServerSide": false,
"sServerMethod": "POST",
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "idbom", "value": window.id_bom } );
},
"sAjaxSource": "<?=base_url()?>index.php/master_bj/ambilbomproses",
"sAjaxDataProp": "callback",
"bDestroy": true,
"bAutoWidth": false,
"aoColumns": [
{ "sTitle": "ID Proses", "mDataProp": "id_proses_produksi"},
{ "sTitle": "Nama Proses", "mDataProp": "nama"},
{ "sTitle": "Lama Proses", "mDataProp": "waktu"},
{ "sTitle": "Jumlah Mesin", "mDataProp": "jumlah_mesin"},
]
} );
} );
$('#btnuptambahproses').click(
Otableupproses.fnAddData( [$('#prosesupbj').val(),$("#prosesupbj option:selected").text(),$('#txtuplamaproses').val(),$('#txtupjmlmesin').val()]
);
});
my controller name master_bj
function ambilbomproses()
{
$idbom= $this->input->post('idbom');
$res['dataproses']=$this->bom_punya_proses_model->getbomproses($idbom);
echo json_encode(array("callback" => $res['dataproses']));
}
how can i dinamically add new row ?
i use fnAddData() it not work because i get data from json
please help
my model class name bom_punya_proses_model
function getbomproses($idbom)
{
$sql= "SELECT proses_produksi_punya_bom.id_proses_produksi, proses_produksi.nama, proses_produksi_punya_bom.waktu, proses_produksi_punya_bom.jumlah_mesin
FROM proses_produksi_punya_bom
INNER JOIN proses_produksi ON proses_produksi_punya_bom.id_proses_produksi = proses_produksi.id_proses_produksi
WHERE proses_produksi_punya_bom.id_bom = '".$idbom."'";
$result= $this->db->query($sql);
if($result->num_rows() > 0){
return $result->result_array();
}else
return false;
}
no problem with my query and controller , because the json has been performed correctly , but the problem is when i try to add new row data to table ,
Your model does not appear to be using the active records portion of the codeigniter framework at all.
Check the tutorial on the CI website and have a look at the active record help page at :
http://ellislab.com/codeigniter/user-guide/database/active_record.html
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).
This question is regarding the plugin found here: http://www.datatables.net/usage/columns
var hidecols = '{"sClass": "Hide", "aTargets": [0]},{"sClass": "asdf", "aTargets": [1]},{"sClass": "qwer", "aTargets": [2]}';
var hidecolsobj = eval('(' + hidecols + ')');
var oTable = $('#MainContent_OverviewTable').dataTable({
"sPaginationType": "full_numbers",
"bProcessing": true,
"bServerSide": true,
"aoColumnDefs":
[
hidecolsobj, // <--------- *** HERE ***
],
"sAjaxSource": "Services/Service.svc/GetDataTableOutputOverview",
"fnServerData": function (sSource, aoData, fnCallback) {
var jsonAOData = JSON.stringify(aoData);
$.ajax({
type: "POST",
async: true,
url: sSource,
contentType: "application/json; charset=utf-8",
data: '{"Input":' + jsonAOData + '}',
dataType: "json",
success: function (msg) {
fnCallback(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.responseText);
}
});
}
});
So the code works fine with no errors but the class "qwer" is the only one that is being applied to my table. I tested this out and it only applies the class that appears last in my list of objects. I would like each of the columns to have the classes defined in the hidecols variable. How can I do that?
This is how it appears in the documentation from the Datatables website:
$('#example').dataTable( {
"aoColumnDefs": [
{ "sClass": "my_class", "aTargets": [ 0 ] }
]
} );
EDIT:
"aoColumnDefs":
[
{ "sClass": "Hide", "aTargets": [0] },
{ "sClass": "asdf", "aTargets": [1] },
{ "sClass": "qwer", "aTargets": [2] }
],
The above edit works properly but this isn't an option for me. I need to be able to build the string hidecols dynamically.
You are passing DataTables a string for the aoColumnDefs parameter. Just remove the quote marks around the hidecols "string" to make it an array of objects. That will remove the need for the evil (eval).
var hidecols = [{"sClass": "Hide", "aTargets": [0]},{"sClass": "asdf", "aTargets": [1]},{"sClass": "qwer", "aTargets": [2]}];
Allan
Ah! I figured out how to do it!
Instead of doing this:
"aoColumnDefs":
[
hidecolsobj, // <--------- *** HERE ***
],
I should be doing this:
var hidecols = '[{"sClass": "Hide", "aTargets": [0]},{"sClass": "asdf", "aTargets": [1]},{"sClass": "qwer", "aTargets": [2]}]';
var hidecolsobj = eval('(' + hidecols + ')');
"aoColumnDefs": hidecolsobj, // <--------- *** HERE ***