How to pass textbox value by ServerSide datatable ajax call in MVC5 - javascript

I have a server side data-table.
When I make an ajax call, it does not send the given value in the text-box, it sends empty.
When I pass static data it's working fine.
This is fine:
var table = $("#tblUsers").DataTable({
"language":
{
"processing":
"<div class='overlay custom-loader-background'><i class='fa fa-cog fa-spin custom-loader-color'></i></div>"
},
"processing": true,
"serverSide": true,
"ajax":
{
"url": "/Client/GetData",
"type": "POST",
"dataType": "JSON",
'data': ({ ZoneID: zoneIDs })
},
"columnDefs": [
{
"targets": [0],
"width": "5%",
"hidden": true,
}
],
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
//console.log(nRow);
$(nRow).find("td:eq(0)").attr("hidden", true);
return nRow;
},
"columns": [
{
"data": "ClientDetailsID"
}]
});
But when I pass zoneid from textbox value instead of static data it sends empty.
"data": { ZoneID: $("#txtSOmething").val() }

Change your data to
data: function(d){
d.myValue = $("#txtSOmething").val();
}
The on the server look for myValue in the Request. For example, asp mvc: Request.Form.Get("myValue")

Related

Pass Parameters through ajax call - ajax url

I am trying to pass value parameter through the ajax call to the controller. It is a date value. I am struggling to find a way to pass parameters through this ajax url. Please help.
function dataTable() {
var value = $("#somedatevalue).val();
$("#thisTable").DataTable({
"processing": true,
"paging": false,
"language": {
processing: "<span class='processing-message'><i class='fa fa-circle-o-notch fa-spin'></i> Processing...</span>"
},
ajax: {
url: $('table#thisTable').data("ajaxurl"),
type: "POST",
datatype: "json",
},
"columns": [
{
"data": "column1",
},
{
"data": "column2",
},
{
"data": "column3",
},
{
"data": "column4",
},
{
"data": "column5",
},
{
"data": "Url",
"render": function (data) {
return '<a class="btn btn-info" href="' + data + '">Select</a>';
}
}
],
"dom": 't<"col-lg-3"l><"col-lg-6"p><"col-lg-3"i>'
});
}
You can pass value as query parameter like http://www.url.com?date="17-02-21"
If you are using php use can get the value as $_GET['date']
If you are using node js, you can get value as req.query.date
Consider the following.
function dataTable() {
$("#thisTable").DataTable({
"processing": true,
"paging": false,
"language": {
processing: "<span class='processing-message'><i class='fa fa-circle-o-notch fa-spin'></i> Processing...</span>"
},
"ajax": {
"url": $('table#thisTable').data("ajaxurl"),
"type": "POST",
"data": { "someDate": $("#somedatevalue").val() },
"datatype": "json"
},
"columns": [
{
"data": "column1",
},
{
"data": "column2",
},
{
"data": "column3",
},
{
"data": "column4",
},
{
"data": "column5",
},
{
"data": "Url",
"render": function (data) {
return '<a class="btn btn-info" href="' + data + '">Select</a>';
}
}
],
"dom": 't<"col-lg-3"l><"col-lg-6"p><"col-lg-3"i>'
});
}
First you must address the Typo in your jQuery Selector. Then you can adjust your Ajax parameters to include a data.
See more here: https://datatables.net/reference/option/ajax.data
In principle it operates in exactly the same way as jQuery's $.ajax.data property, in that it can be given as an object with parameters and values to submit, but DataTables extends this by also providing it with the ability to be a function, to allow the data to be re-evaluated upon each Ajax request (see above).

error 500 on jquery datatables search

i created a table with jquery datatables. when I want to filter my table with search bar, the browser gives me an alert DataTables warning: table id=grid - Ajax error. For more information about this error, please see http://datatables.net/tn/7.
this is my code :
$("#grid").dataTable({
"processing": true, // control the processing indicator.
"serverSide": true, // recommended to use serverSide when data is more than 10000 rows for performance reasons
"info": true, // control table information display field
"stateSave": true, //restore table state on page reload,
"searching": true,
"language": {
"url": "/translate/datatables.fa-IR.json"
},
"lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "All"]], // use the first inner array as the page length values and the second inner array as the displayed options
"ajax": {
"url": serviceBase + "/Auth/Admin/SearchOrders2/",
"type": "GET",
'beforeSend': function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + localStorageService.get("authorizationData").token);
}
},
"columns": [
{ "data": "customerContact", "orderable": true },
{ "data": "isDone", "orderable": true },
{
"mRender":
function (data, type, row) {
var xxx = $scope.name1 = $filter("jalaliDateFromNow")(row["createdDate"]);
return "<span>" + $filter("jalaliDateFromNow")(row["orderCreationTime"]); +'</span>';
}, "orderable": true
},
{ "data": "totalPrice", "orderable": true },
{ "data": "count", "orderable": true },
{ "data": "description", "orderable": true },
{
"mRender": function (data, type, row) {
return '<button class="btn btn-sm btn-circle green tooltips" disabled="disabled"><i class="fa fa-check"></i><span>جزئیات</span></button>'
},
"orderable": false
}
],
"order": [[0, "desc"]]
});
which part of my code is wrong?

Update ajax data programatically for jQuery datatables

I have a jQuery datatable with an ajax datasource defined like so:
var selected_ids = [];
selected = $('#selected_members').dataTable( {
"ajax": {
'type': 'GET',
'url': "{!! route('admin.members.included_datatables') !!}",
'data': {
'member_ids' : JSON.stringify(selected_ids)
},
},
"processing": true,
"serverSide": true,
"columns": [
null,
null,
null,
null,
null,
{"searchable": false, "orderable": false}
]
});
$('#available_members').on('click', '.select', function(e) {
e.preventDefault();
member_id = $(this).data('member-id');
selected_ids.push(member_id);
selected.api().ajax.reload();
});
As you can see I am updating the contents of selected_ids manually and I want to then refresh the datatable. This is working except that when the datatable reloads and does the ajax call the member_ids parameter that it passes to the server is still empty. Do I have to update the data property of the ajax call manually before reloading the table and if so how do I do that?
I fixed it I used a closure for the data attribute instead like so:
selected = $('#selected_members').dataTable( {
"ajax": {
'type': 'GET',
'url': "{!! route('admin.members.included_datatables') !!}",
'data': function ( d ) {
d.member_ids = selected_ids;
return d;
}
},
"processing": true,
"serverSide": true,
"columns": [
null,
null,
null,
null,
null,
{"searchable": false, "orderable": false}
]
});

jquery data table and sorting columns

I'm using jquery data table to display large amounts of data inside grid. I implemented server side pagination but I'm struggling with sorting data server side.
Below is my datatable initialization, answer with query for sorting is not the subject here, I just need a way to pass information of which column is clicked to the controller, the one upon I will do the sorting.
('#myTable').dataTable({
"processing": true,
"serverSide": true,
"info": false,
"pageLength": 10,
"lengthChange": false,
"stateSave": false,
"bPaginate": true,
"bFilter": false,
"sPaginationType": "full_numbers",
"info": "Page _PAGE_ from _PAGES_",
"infoEmpty": "No data",
"oPaginate": {
"sFirst": "First",
"sPrevious": "Previous",
"sNext": "Next",
"sLast": "Last"
},
"ajax": {
"url": "#string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))/MyController/GetData",
"type": "GET",
"data": function (d) {
.....
},
},
preDrawCallback: function (settings) {
...
},
drawCallback: function (settings) {
...
},
"columns": [
{ "data": "Id" },
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "Age" }
],
"columnDefs": [
{
targets: [0],
orderable: false
},
{
render: function (data, type, row) {
...
}
],
"order": [[0, "desc"]]
});
public ActionResult GetData(){
var sortColumn = ...
...
}
You can bind the 'order' event like this:
$('#myTable').on( 'order.dt', function () {
var order = table.order();
var column_selected = order[0][0];
var order_way= order[0][1];
doStuff(column_selected ,order_way);
});
See it in plugin reference
By specifying "serverSide": true,, datatables will by default add information to the request which you need to use in your server-side code. If you look in the Firebug Network panel, you will be able to see the request with the querystring parameters. See here for the full list of parameters. Note that the link is to the v1.9 documentation, because that's what it looks like you're using.
So for sorting, you'd be interested in iSortCol_0 and sSortDir_0 which relate to the clicked column and the sort direction respectively.
In your controller method, you would access the parameters like this:
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
var sortColumnDir = Request["sSortDir_0"];
You then need to incorporate this, and the other parameters into your query.
Here is an article on using server-side datatables with MVC

How to send form data along with jQuery DataTables data in server-side processing mode

I am trying to post form data without success and data couldn't be loaded.
How can I pass all form data with array and single textbox, combobox, etc. to fnServerdata?
table_obj = $('#group-table').dataTable({
"sAjaxSource": "URL Goes here",
fnServerData: function(sSource, aoData, fnCallback,oSettings) {
oSettings.jqXHR = $.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource+'?'+$.param(aoData),
"data": $("#frm").serializeArray(),
"success": fnCallback
} );
},
aaSorting: [[ 1, "desc" ]],
bProcessing: true,
bServerSide: true,
processing : true,
columnDefs: [{
'targets': 0,
'searchable':false,
'orderable':false,
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<label><input type="checkbox" name="user_id[]" value="' + $('<div/>').text(data).html() + '"></label>';
}
}],
rowCallback: function(row, data, dataIndex){
// If row ID is in list of selected row IDs
if($.inArray(data[0], rows_selected) !== -1){
$(row).find('input[type="checkbox"]').prop('checked', true);
$(row).addClass('selected');
}
},
iDisplayLength: '50',
});
If you want to format the POST data, you can also format the form data using jquery .each() function. Let me use the answer above using solution #1 but with jquery .each() to format the data.
$('table').DataTable({
"ajax": {
"url": "URL HERE",
"type": "POST",
"data": function(d) {
var frm_data = $('form').serializeArray();
$.each(frm_data, function(key, val) {
d[val.name] = val.value;
});
}
}
});
Then you can just access that in PHP like:
var $data = $_POST['name'];
SOLUTION 1
Replace this:
$('#group-table').dataTable({
"sAjaxSource": "URL Goes here",
fnServerData: function(sSource, aoData, fnCallback,oSettings) {
oSettings.jqXHR = $.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource+'?'+$.param(aoData),
"data": $("#frm").serializeArray(),
"success": fnCallback
} );
},
with:
$('#group-table').dataTable({
"ajax": {
"url": "URL Goes here",
"type": "POST",
"data": function(d){
d.form = $("#frm").serializeArray();
}
},
Your form data will be in form parameter as an array of objects with parameters name and value, below is JSON representation:
"form": [{"name":"param1","value":"val1"},{"name":"param2","value":"val2"}]
SOLUTION 2
If you want to have form data as name/value pairs, see this jsFiddle for an example of alternative solution.
NOTES
There are checkboxes in your data table. Solution above will not work for form elements in the data table, because DataTable removes non-visible nodes from DOM.
How about this?
$('#group-table').DataTable( {
"processing": true,
"serverSide": true,
"bDestroy": true,
"bJQueryUI": true,
"ajax": {
"url": "url here",
"type": "POST",
"data": {
store: $('#store').val(),
month: $('#m').val(),
year: $('#y').val(),
status: $('#status').val(),
},
}
} );
then you can access the sample data above through PHP using this.
$_POST['store']
$_POST['month']
$_POST['year']
$_POST['status]
Hope that helps.

Categories

Resources