Jquery Datatables adding parameter to request - javascript

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

Related

Datables serverSide ajax POST 'error': "int() argument must be a string, a bytes-like object or a number, not 'NoneType'"

now i got some error when i try to get data and display on the datatables which using serverSide.
following to my code below i have get my data by using ajax POST method because i want to send some data that need to use to filter in my database, and this is my code.
Javascript
report_table = $('#report_table').DataTable({
"scrollX": true,
"serverSide":true,
"deferRender": true,
"ajax": {
"url": "load_report_table",
"type": "POST",
"data":{
'region_id': function() { return $('#select_reg').val() },
}
},
});
Python
from datatables import ColumnDT, DataTables
from flask import request
#app.route('/load_report_table', methods=['POST', 'GET'])
def load_report_table():
reg_id = request.form['region_id']
columns = [
ColumnDT(Battery_Log.time),
ColumnDT(Battery.serial_number),
ColumnDT(Battery_Log.usage),
]
query = db.session.query().select_from(Battery, Battery_Log)\
.filter(Battery.reg_id == reg_id, Battery_Log.battery_id == Battery.id)
params = request.args.to_dict()
rowTable = DataTables(params, query, columns)
return rowTable.output_result()
but when i print rowTable.output_result() it got the error like this.
{'draw': '1', 'recordsTotal': '14733', 'recordsFiltered': '14733', 'error': "int() argument must be a string, a bytes-like object or a number, not 'NoneType'"}
For now i guess the error that cause by using POST method because when i have change my code to call only url and not post any data to the route function it work normally, the code is show below.
report_table = $('#report_table').DataTable({
"scrollX": true,
"serverSide":true,
"deferRender": true,
"ajax": "load_report_table"
});
So are there anyway to fix that i can POST my data to my route function and return the data to show on the datatables.

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

Data Tables get JSON from API without setting "aaData"

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"
} );
} );

The confuse about use jquery $.ajax to read javascript file

suppose I have a config javascript file:
window.Config = {};
Config.UI = {
"Area": {},
"Layer": {},
"Sprites": {},
"Audio": {}
};
Config.UI.Area = {
"prop": {
"uuid": {
"_type": "string",
},
"frame": {
"_type": "rect",
"_value": {
"x": "0",
},
"_aka": "frame"
},
"zIndex": {
"_type": "string",
}
},
then I want use $.ajax to read this file:
$.ajax({
url:'js/config.js',
success:function (data, textStatus) {
console.log(data);
}
})
the question is how can I get some key's value in the config,by use the data $.ajax return?
like the "Config.UI" or the 'uuid' in ui.area.prop?Or can I convert them to json?
Rather than use AJAX, why not just insert a script?
var script = $('<script>');
script.attr('type', 'text/javascript');
script.attr('src', 'js/config.js');
script.bind('load', function() {
// use window.Config
});
script.appendTo('head');
icktoofay has a good suggestion, and the issue with the jQuery.ajax call looks to be a missing dataType: 'script' option which will evaluate the response and should give you object access. You might want to look into jQuery.getscript() as well.
I find it very useful and powerful to store data on the server as javascript objects and read them using Ajax. And it is very easy to do. Let me give you an example from an educational application I have written.
This is an example table of contents file (l1contents.js) that I would store on the server:
{
title : "Lesson 1",
topics : [
{name : "Topic 1", file : "l1t1data.js" },
{name : "Topic 2", file : "l1t2data.js" },
]
}
This is the javascript code I use to process the file:
$.ajax({
url : contentsFileName, // would be set to 'l1contents.js'
dataType : 'text', // yes this is correct, I want jquery to think this is text
cache : false,
success: function(data) {
var contentsObj = eval('(' + data + ')');
var lessonTitle = contentsObj.title;
for (var i = 0; i < contentsObj.topics.length; i++) {
var topic = contentsObj.topics [i];
// process topic.name and topic.file here
}
}
});
Obviously, this is simplified, but hopefully you get the idea. I simply use eval to set the object. And note that I don't even need any javascript code defining the structure of contentsObj. (I, of course, do have extensive comments defining the structure of my objects, but they are simply comments, not code.)
if your json file contains json data than you can use parseJSON() , toJSON() method.
and another solution is use eval(), this conver json data to javascript object so you can easly get a value by giving key.

Categories