Add ajax data on DataTable before send - javascript

I initialized the DataTable in a variable:
var dataTable = $("#selector").DataTable({
processing: true,
serverSide: true,
ajax: $.fn.dataTable.pipeline({
dataType: "json",
url: "/path/ajaxurl",
data: {
"fruits": "apple",
"veggies": "banana",
},
dataSrc: "data"
}),
sPaginationType: "extStyle"
});
Now, somewhere in my script I have this checkbox that when changed will add a new data on the ajax above then initialize the draw():
$(document).on("change", "#add-some-liquors", function(e) {
// some validations here
// My attempt to add this data
dataTable.data({"drinks" : "coca-cola"});
// Draw the dataTables
dataTable.clearPipeline().draw();
});
Seems that dataTable.data({"drinks" : "coca-cola"}); does not add the drinks on the POST when I checked on the backend, I only get the apple & banana which is the two default initialized data. What am I missing?

According to the API .data method is only for retrieving. Try holding data in a variable, updating that object and then using it in .ajax method.
var items = {}
ajax: $.fn.dataTable.pipeline({
dataType: "json",
url: "/path/ajaxurl",
data: items,

Declare your data as a variable and add the drinks value later.
var data = {
"fruits": "apple",
"veggies": "banana",
};
console.log(data);
//On the click event
$('#chk').on('click', function() {
if ($(this).is(':checked')) {
data['drinks'] = 'coca-cola';
} else {
//When unchecking the option, set it's value to null
data['drinks'] = null;
//Or delete the property.
//delete data['drinks'];
}
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="chk" />

The ajax.data object can be initialized as a function. The function will be evaluated each time the data is fetched. In this example, the value of the global variable selectedDrink will be sent with the ajax request as the drinks field.
var selectedDrink = "";
var dataTable = $("#selector").DataTable({
processing: true,
serverSide: true,
ajax: $.fn.dataTable.pipeline({
dataType: "json",
url: "/path/ajaxurl",
data: function(d) {
d.fruits = "apple";
d.veggies = "banana";
d.drinks = selectedDrink;
},
dataSrc: "data"
}),
sPaginationType: "extStyle"
});
$(document).on("change", "#add-some-liquors", function(e) {
selectedDrink = "coca-cola";
// Draw the dataTables
dataTable.clearPipeline().draw();
});

Related

How to get current table id to add to ajax data when initialisation is used for multiple tables?

I have the following initialisation for multiple tables with the same class but different id attributes:
var $table = $('table.jobs');
$table.DataTable({
....
ajax: {
url: '/my-url',
dataSrc: function (json) {
return json.data
},
data: function(data) {
data.table_id = $table.attr('id');
// gives the same id for all tables
}
},
...
});
Is there a way I can identify which table is sending the ajax request? I'm trying to avoid duplicating the entire initialisation for every table.
You can try something like this:
$('.table.jobs').each(function () {
$('#'+$(this).attr('id')).dataTable({
url: '/my-url',
dataSrc: function (json) {
return json.data
},
data: function(data) {
data.table_id = $table.attr('id');
// gives the same id for all tables
}
});

jquery Datatables filter rows

Hi I have a DataTables DataTable object which requests json data via an ajax call. Each object inside the json data has a property called state that can be one of a number of values. Ultimately, I'd like to create several (Data)tables, one for each state without having each table request the same data via ajax again and again. For now, I haven't managed to make a single table filter out the rows with incorrect state yet and I'd like to solve this problem first.
The DataTable object defined as follows:
$(document).ready(function () {
var table = $('#example').DataTable({
data: example,
ajax: {
url: "{{ callback_url }}",
dataType: 'json',
dataSrc: '',
},
createdRow: function (row, data, index) {
},
columns: [{
data: "Type"
}, {
data: "State",
}
}]
});
});
I want to filter the data that comes from the ajax call based on a parameter (e.g. "if (row.State == 'new') {...};"). How can I do that? Does datatables have a function that can be passed to filter each row?
I really need several tables which show data from the same ajax callback but in different states (e.g. a "New" table, an "Old" table etc.). How can I do this without requesting the same json data again and again for each table rendered? Ideally I can store the ajax in a variable but with the async process I'm not sure how this will work out.
You can use one ajax and store the data, and than create each datatable.
Example:
$(document).ready(function () {
var data = null;
$.ajax(URL, {
dataType: 'json',
success: function(ajaxData){
data = ajaxData;
newData = data.filter(function(item){ return item.State == "New"});
oldData = data.filter(function(item){ return item.State == "Old"});
var newTable = $('#newTable').DataTable({
data: newData,
});
var oldTable = $('#oldTable').DataTable({
data: newData,
});
}
});
}

Datatables won't reload json data

Not only should this be a straightforward operation but I'm following the documentation as well. I have an ajax call that returns a json data set. I've cleared the table successfully but when the success method is called nothing happens. The console statement shows that data is being returned... however the table remains empty. Any idea why?
JS
$('#SortByCoverage').click(function () {
var table = $('#theTable').DataTable();
table.fnClearTable();
$.ajax({
url: '/Home/Question2',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
$("#thetable").dataTable({
"aaData": data,
"aoColumns": [
{title:"AdId"},
{title:"BrandId"},
{title:"BrandName"},
{title:"NumPages"},
{title:"Position"}
]
});
}
});
Server Side Code
public JsonResult Question2()
{
var ads = _client.GetAdDataByDateRange(new DateTime(2011, 1, 1), new DateTime(2011, 4, 1));
var json = ads.Where(x => x.Position.Equals("Cover") && x.NumPages >= (decimal)0.5).Select(x => new{
AdId = x.AdId,
BrandId = x.Brand.BrandId,
BrandName = x.Brand.BrandName,
NumPages = x.NumPages,
Position = x.Position
});
return Json(json, JsonRequestBehavior.AllowGet);
}
Sample Data (client side)
EDIT
As pointed out in the comments I misspelled the element name dataTable in the success callback. However, now I'm getting the following error:
Cannot reinitialise DataTable. To retrieve the DataTables object for this table, pass no arguments or see the docs for bRetrieve and bDestroy
Do I really have to destroy the table, once it's clear, to reload the data?
I added the bRetrieve and bDestroy. This got rid of the error but still no new data loaded into the table.
$.ajax({
url: '#Url.Action("Question2", "Home")',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
$("#theTable").dataTable({
//"bRetrieve": true,
"bDestroy": true,
"aaData": data,
"aoColumns": [
{title:"AdId"},
{title:"BrandId"},
{title:"BrandName"},
{title:"NumPages"},
{title:"Position"}
]
});
}
});
I would make a little different, see how:
var theTable = $("#thetable").dataTable({
"aaData": [],
"aoColumns": [
{data:"AdId"},
{data:"BrandId"},
{data:"BrandName"},
{data:"NumPages"},
{data:"Position"}
]
}).DataTable();
$('#SortByCoverage').click(function () {
$.ajax({
url: '/Home/Question2',
type: 'GET',
dataType: 'json',
success: function (data) {
theTable.clear().draw();
table.rows.add(data)
.draw();
}
});

Persist additional dataSource.read parameters on paganation in Kendo data grid

I have a Kendo Grid that loads data via ajax with a call to server-side ASP.NET read method:
public virtual JsonResult Read(DataSourceRequest request, string anotherParam)
In my client-side JS, I trigger a read when a button is clicked:
grid.dataSource.read( { anotherParam: 'foo' });
grid.refresh();
This works as expected, only I lose the additional param when I move through the pages of results in the grid, or use the refresh icon on the grid to reload the data.
How do I persist the additional parameter data in the grid?
I have tried setting
grid.dataSource.data
directly, but without much luck. I either get an error if I pass an object, or no effect if I pass the name of a JS function that returns data.
if you want to pass additional parameters to Read ajax datasource method (server side), you may use
.DataSource(dataSource => dataSource
...
.Read(read => read.Action("Read", controllerName, new { anotherParam= "foo"}))
...
)
if you want to pass additional parameters through client scripting you may use datasource.transport.parameterMap, something as below
parameterMap: function(data, type) {
if (type == "read") {
return { request:kendo.stringify(data), anotherParam:"foo" }
}
Use the datasource.transport.parameterMap
parameterMap: function(data, type) {
if (type == "read") {
return kendo.stringify(data, anotherParam);
}
I'm not sure where your other param is coming from, but this is generally how I send extra parameters to the server.
http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#configuration-transport.parameterMap
if use datasource object :
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '/Api/GetData',
contentType: "application/json; charset=utf-8", // optional
dataType: "json",
data: function () {
return {
additionalParam: value
};
}
},
//parameterMap: function (data, type) {
// and so use this property to send additional param
// return $.extend({ "additionalParam": value }, data);
//}
},
schema: {
type: "json",
data: function (data) {
return data.result;
},
},
pageSize: 5,
serverPaging: true,
serverSorting: true
});
and set options in grid:
$("#grid").kendoGrid({
autoBind: false,
dataSource: dataSource,
selectable: "multiple cell",
allowCopy: true,
columns: [
{ field: "productName" },
{ field: "category" }
]
});
and in click event this code :
dataSource.read();
and in api web method this action:
[HttpGet]
public HttpResponseMessage GetData([FromUri]KendoGridParams/* define class to get parameter from javascript*/ _param)
{
// use _param to filtering, paging and other actions
try
{
var result = Service.AllCustomers();
return Request.CreateResponse(HttpStatusCode.OK, new { result = result });
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, new { result = string.Empty });
}
}
good luck.
To persist the updated value of the additional parameter through pagination, you will need to create a global variable and save the value to it.
var anotherParamValue= "";//declare a global variable at the top. Can be assigned some default value as well instead of blank
Then, when you trigger the datasource read event, you should save the value to the global variable we created earlier.
anotherParamValue = 'foo';//save the new value to the global variable
grid.dataSource.read( { anotherParam: anotherParamValue });
grid.refresh();
Now, this is important. In your datasource object transport.read.data must be set to use a function as shown below:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '/Api/GetData',
contentType: "application/json; charset=utf-8", // optional
dataType: "json",
//Must be set to use a function, to pass dynamic values of the parameter
data: function () {
return {
additionalParam: anotherParamValue //get the value from the global variable
};
}
},
},
schema: {
type: "json",
data: function (data) {
return data.result;
},
},
pageSize: 5,
serverPaging: true,
serverSorting: true
});
Now on every page button click, you should get the updated value of the anotherParam which is currently set to foo

Display data from json array using ajax

I have the following code on index page the script contains part of the code that will call the data from test page
<div class="leftbox" id="proddisplay">
</div>
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test.php',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#proddisplay').html(returndata);
console.log(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
From test.php i am getting json array that looks like this
[1,2,"text","text2"]
I want to display the json array data in a tabular form and display it inside the div. the view of table should be something like this (it will have some css of its own)
static text: 1
static text: 2
static text: text
static text: text2
static text will be given by me and remains the same throughout however the values of array would change. can anyone tell how i can do so
individually i can display the data from json, but here i also need to put json data in a table and then put that table within a div
First of all you need to encode the array in php before sending to frontend, use json_encode() and then decode it in the success function using JSON.parse() . After just run a loop throught the array.
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test.php',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
var returneddata = JSON.parse(returndata);
var htmlData= '';
for(var i=0; i<returneddata.length; i++){
htmlData+= 'static text: '+returneddata[i]+' <br>';
}
$('#proddisplay').html(htmlData);
console.log(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});

Categories