How to use datatables in ajax - javascript

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

Related

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 !!

get the ID of specific row in JQuery datatable

I have JQuery table like following image
I want to alert the ProductID once I click V link text in Action column
<table id="productTable">
<thead>
<tr>
<th>ProductID</th>
<th>TitleEN</th>
<th>TypeEN</th>
<th>ModifiedDate</th>
<th>Actions</th>
</tr>
</thead>
</table>
#* Load datatable css *#
<link href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet" />
#section Scripts{
#* Load DataTable js here *#
<script src="//cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("#productTable").DataTable({
"info": false,
"processing": true,
"serverSide": true,
"filter": false,
"orderMulti": false,
"ajax": {
"url": "/Home/LoadProductData",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "Product_ID", "name": "Product_ID", "autoWidth": true },
{ "data": "Product_Title_EN", "name": "Product_Title_EN", "autoWidth": true },
{ "data": "Product_Type_EN", "name": "Product_Type_EN", "autoWidth": true },
{ "data": "ModifiedDate", "name": "ModifiedDate", "autoWidth": true },
{
data: null,
className: "center",
defaultContent: ' V '
}
]
});
});
$('#editor_view').on('click', 'a.editor_view', function (e) {
alert($("data-Product_ID").val());
});
</script>
}
currently I alerted its like this
alert($("data-Product_ID").val());
but it cant get the ID of that, hw can I do this ?
this is the html for table row
<tr class="even" role="row">
<td class="sorting_1">02</td>
<td>Current Accounts</td>
<td>Assets</td>
<td></td>
<td class=" center">
<a class="editor_view" href="#"> V </a>
</td>
Change your script to
$("#productTable").on('click', '.editor_view', function() {
var ID = $(this).closest('tr').find('td').eq(0).text();
alert(ID);
});
Note that your dynamically generating the table rows so you need event delegation attached to an element that exists in the DOM when the view is first generated (i.e the element with id="productTable").
Below is my Data table.
table_low_stocks.dataTable({
"bLengthChange": true,
"processing": false,
// "serverSide": true,
"bPaginate": false,
"bInfo": false,
"iDisplayLength" : 5,
"bSort" : true,
"ajax": {
'type': 'POST',
'url': "<?=action('AdvertiserproductsController#postLowstockproducts')?>"
},
"columns": [
/* {"data": "sr_no"}, */
{"data": "product_name"},
{"data": "inventory"},
{"data": "update"}
] // set first column as a default sort by asc
});
This is how i am rendering the HTML (Datatable from Controller )
return Datatables::of($data)
->add_column('action','<a data-productid="{{$sr_no}}" class="label label-sm label-messages-btn update-product"> <i class="fa fa-pencil-square-o"></i> Update Stock </a>')
->make(true);
If you have seen above i have given data-productid="{{$sr_no}}" to a tag
so ultimately that is what you have to give anyhow,.
Now from the jquery part.what have done is .
$(document).on("click",".update-product", function(e){
e.preventDefault();
var getProductId = $(this).data("productid");
alert(getProductId);
});
and i got the product Id :-)
to give data attribute do like
data-productid="{{$sr_no}}"
and to get the data attribute u have to use
$(selector).data("productid");
Hope this is helpfull to you.
$('#editor_view').on('click', 'a.editor_view', function (e) {
alert($("data-Product_ID").val());
});
Here you have used "editor_view" as ID and I can view it is set as a class, so it will not work. It should be like
$('.editor_view').on('click', 'a.editor_view', function (e) {
alert($("data-Product_ID").val());
});

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 warning (table id = 'example'): Requested unknown parameter '0' from the data source for row 0

i am very new to javascript and jquery and using data table to show server data. i am using below code.
$(document).ready(function () {
$("#example").dataTable({
"bProcessing": true,
"sAjaxSource": "/admin/vskuStatusUid?uploadId=" + $('#UID').val(),
"aoColumns": [{
"mData": "uid"
}, {
"mData": "vcode"
}, {
"mData": "vsku"
}, {
"mData": "timeStamp"
}, {
"mData": "state"
}, {
"mData": "counter"
}]
});
});
and my ajax response looks like below
{
"aaData": [
{
"uid": "UID0000007017",
"vcode": "927ead",
"vsku": "Prateek1000",
"timeStamp": 1391158258658,
"state": "VENDOR_PRODUCT_PERSISTENCE_COMPLETED",
"counter": 2
},
{
"uid": "UID0000007017",
"vcode": "927ead",
"vsku": "Prateek5000",
"timeStamp": 1391158258881,
"state": "VENDOR_PRODUCT_PERSISTENCE_COMPLETED",
"counter": 3
}
]
}
and my hmtl code is below
<table id="example">
<thead>
<tr>
<th>Upload Id</th>
<th >Vcode</th>
<th>Vsku</th>
<th>Timestamp</th>
<th>State</th>
<th>counter</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
can someone help me out here.
i have checked other answer related to this question and mostly all were indicating the problem might be difference in thead total column and mdata.
you dont need to write the columns in the html, dataTable does it for you. the only html you need is <table id="example"></table>
i think there error is the you insert data partially or trying to get data from unexisted row in the table.
here is a possible fix :
after you grab the data you got and parse it to object. you can do something like this:
var table = $("#example").dataTable({
"bProcessing": true,
"sAjaxSource": "/admin/vskuStatusUid?uploadId=" + $('#UID').val(),
"aoColumns": [{
"mData": "uid"
}, {
"mData": "vcode"
}, {
"mData": "vsku"
}, {
"mData": "timeStamp"
}, {
"mData": "state"
}, {
"mData": "counter"
}]
});
for (var i=0; i< ParsedObject.length; i++) {
var temp_item = ParsedObject[i]; //new row data
table.fnAddData(temp_item.uid, temp_item.vcode, temp_item.vsku, temp_item.timeStamp, temp_item.state, temp_item.counter); //adds new row to datatable
}

Trying to insert JSON data into a datatable widget

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).

Categories