Data Tables get JSON from API without setting "aaData" - javascript

I am using Data Tables and I get my data like it is shown in example
$('.data-table').dataTable({
"bProcessing": true,
"sAjaxSource": "/api/item/list",
"aoColumns": [
{ "mData": "Title" },
{ "mData": "Price" }
]
});
However there is a problem, I need to take all my objects and wrap them in aaData for this to work like so
[HttpGet]
public dynamic List()
{
var items = _db.Items.OrderBy(x => x.ID);
var a = new {
aaData = items
};
return a;
}
And this is bad for obvious reason that I need to modify my back-end for this instead of returning plain-old JSON. I've tried setting aaData instead of sAjaxSource but got errors and it didn't worked. Any ideas on how can I fix this?

Instead of the property aaData, you can tell DataTables to use another property name with the sAjaxDataProp parameter. For example:
// Get data from { "data": { "inner": [...] } }
$(document).ready( function() {
var oTable = $('#example').dataTable( {
"sAjaxSource": "sources/data.txt",
"sAjaxDataProp": "data.inner"
} );
} );

Related

DataTables not showing data

Hi I have the following data but cannot get DataTables to display it:
const data = [{
"School":"Arsenal 2011",
"Group":{
"Name":"Previous",
"ParentGroup":{
"Name":"Arsenal",
"ParentGroup":{
"Name":"USA",
"ParentGroup":null
}
}
},
"GroupDisplayText":null,
"Publisher":"Abbot",
"PublishedDate":"2011",
"PublishersWebsite":"http://google.com/USA/ADW%202011/Arsenal%202011.pdf"
},
{
"School":"New York 2000",
"Group":{
"Name":"New York",
"ParentGroup":{
"Name":"USA",
"ParentGroup":null
}
},
"GroupDisplayText":null,
"Publisher":"DoE",
"PublishedDate":"2000",
"PublishersWebsite":"http://google.com/USA/New York%202000%20Tables.pdf"
}];
$(document).ready(function () {
$('#example').DataTable( {
"ajax": data
} );
}
I have created a project on playcode
https://playcode.io/470603
I am getting a datatables error
DataTables warning: table id=example - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
I have checked the json and all is ok?
Thanks
$(document).ready(function () {
$('#example').DataTable( {
data:data // ajax for to make ajax request to retrieve data.
"columns": [ // also needs to specify column config to display it
{ "data": "School" },
]
} );
}
for javascript object use data instead.

How can I use ajax.reload with jQuery datatable

I have a requirement to make a search form that will call a web api and populate a jQuery DataTable when a button is clicked. I don't want to load the form until the button is clicked so I have a separate button handler to call my post method. I was told I should use ajax.reload() with this in case someone has to search again to narrow the results but am having some trouble working it into my code. Can anyone assist me with my requirement? My code works fine as is but I would like to know if it can be done more efficiently. See my working code below.
<script>
var dataTable;
var resultsContainer = $('#ResultsContainer');
$(document).ready(function() {
dataTable = $('#SearchResultsTable').DataTable({
"columns": [
{ "data": "clientId" },
{ "data": "lastName" },
{ "data": "firstName" }
],
"language": {
"zeroRecords": '#Resource.NoRecordsFound'
},
"searching": false,
"lengthChange": false
});
});
$('#SearchButton').click(function (e) {
e.preventDefault();
RequestData();
});
function RequestData() {
$.post('#Url.Content("?handler=ClientSearch")', $('#ClientSearchForm').serialize(), function (data) {
ProcessResponse(data);
});
}
function ProcessResponse(data) {
dataTable.clear();
dataTable.rows.add(data);
dataTable.draw();
resultsContainer.addClass('d-block');
}
</script>
It looks like the DataTable ajax.reload method requires the URL for the data to be defined. In the example on https://datatables.net/reference/api/ajax.reload, they use the ajax option in the configuration object to set the URL:
var table = $('#example').DataTable( {
ajax: "data.json"
} );
Then calls to table.ajax.reload() will just pull the updated data in from data.json again. In your case, you're doing a POST to retrieve the data with the search form. So you'll either need to:
use a jQuery ajax object as the value of your DataTable ajax option (see https://datatables.net/reference/option/ajax#object); or
Set ajax.url (https://datatables.net/reference/api/ajax.url) with each search form submission
Hope that helps.

Jquery Datatables adding parameter to request

My problem is that i cannot add a parameter to my request without overwriting the other request parameters.
Example
var table = $('#datatable').DataTable({
"bServerSide": true,
"bProcessing": true,
"ajax": {
"url": "/../",
"data": function ( d ) {
return $.extend( {}, d, {
"iLocked": "this is the only thing i receive"
} );
}
},
........
For refference:
https://datatables.net/reference/option/ajax.data (tried all examples)
The code above nulls all other request parameters that I previously received, like:
sEcho,
sSearch,
iDisplayLength,
iDisplayStart,
iColumns,
iSortingCols
sColumns
I need both those requests and my iLocked property.
I also tried this:
fnServerParams: function (aoData) {
aoData.iLocked = { "name":"iLocked","value":"I don't know where to receive this"};
},
In this case I don't know where to receive this parameter.
Receiving parameters: I receive my parameters in two ways:
Controller parameters: public ActionResult AjaxHandler(TableParams
param,string iLocked)
Request: var customParam= Request.Params.Get("iLocked");*
My basic setup looks like this:
https://www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part#Implementation
My jQueryDataTableParamModel also has the iLocked property.
Question
How do I receive both my new parameter without nulling the previous parameters?
Answer
"sAjaxSource": "/../",
"fnServerParams": function (aoData) {
aoData.push( { "name": "iLocked", "value": "my_value" } );
}
Credit: Sending data to the server with fnServerParams and aoData for jquery DataTable does not work in MVC4
Patrick

jQuery datatable - ASP.NET controller parameter always null

I have the following JavaScript function...
function loadTable(date: string) {
$('#myDataTable').DataTable({
"bServerSide": false,
"sAjaxSource": "Date/GetValuesFromDate",
"data": date
"bAutoWidth": false,
"bProcessing": true,
"aoColumns": [
{ "sName": "MESSAGE" },
{ "sName": "DATE" },
{ "sName": "STATUS" }
]
"bDestroy":true
});
...
That calls the following controller on my ASP.NET WEb Application...
public class DateController : Controller
{
private RegistrationDbContext _context;
public HomeController(RegistrationDbContext context)
{
_context = context;
}
public ActionResult GetValuesFromDate(string date)
{
// Some code here...
return Json(new
{
aaData = results;
});
}
}
However, the value of the string date is always null. I saw that the loadTable() function does contain the date so I have no clue now how to pass that out to the Controller itself...
I hardcoded the date and everything works wonderfull so the only missing piece here is the binding between the JavaScript function and the Controller...
Any pointers?
Thanks!
Trying wrapping up the data param in {} IE
'data': {'date': date}
OR you could directly append it to your source url I think as a query string since it is a GET...
"sAjaxSource": "Date/GetValuesFromDate?date=" + date

ExtJS: return total rows/records in json store

I have a json store that returns values in json format. Now I need to get the number of rows/records in the json string but when I use store.getCount() function it returns 0, but the combobox is populated with rows, and when I use store.length I get undefined, probably because its not an array anymore, its returning from store, which is calling php script. Anyways, whats the best approach for this problem?
Try this out:
var myStore = Ext.extend(Ext.data.JsonStore, {
... config...,
count : 0,
listeners : {
load : function(){
this.count = this.getCount();
}
}
Ext.reg('myStore', myStore);
and then use inside panels:
items : [{
xtype : 'myStore',
id : 'myStoreId'
}]
Whenever you need to get the count then you can simply do this:
Ext.getCmp('myStoreId').count
Your Json response from server, can be something like this...
{
"total": 9999,
"success": true,
"users": [
{
"id": 1,
"name": "Foo",
"email": "foo#bar.com"
}
]
}
Then you can use reader: {
type : 'json',
root : 'users',
totalProperty : 'total',
successProperty: 'success'
} in your store object.
As from docs if your data source provided you can call getTotalCount to get dataset size.
If you use ajax proxy for the store, smth like
proxy : {
type : 'ajax',
url : 'YOUR URL',
reader : {
type : 'json',
root : 'NAME OF YOUR ROOT ELEMENT',
totalProperty : 'NAME OF YOUR TOTAL PROPERTY' // requiered for paging
}
}
and then load your store like
store.load();
There will be sent Ajax asynchronous request, so you should check count in callback like this
store.load({
callback : function(records, operation, success) {
console.log(this.getCount()); // count considering paging
console.log(this.getTotalCount()); // total size
// or even
console.log(records.length); // number of returned records = getCount()
}
});

Categories