DataTables Dynamic displayStart - javascript

I'm trying to get my javascript to use a dynamic value for "displayStart". I'm getting the data from a php script that returns JSON.
Here is my js:
balance.list = function () {
$('#balance').dataTable({
processing: true,
ajax: {
url: 'php/list.php',
dataSrc: 'data'
},
dom: '<"top"flp<"clear">>rt<"bottom"ip<"clear">>',
pageLength: 50,
autoWidth: false,
displayStart: '100',
columns: [
{
width: "10%",
data: "date"
}, {
width: "5%",
data: "checknum"
}, {
width: "75%",
data: "description"
}, {
width: "5%",
data: "debit"
}, {
width: "5%",
data: "credit"
}, {
width: "5%",
data: "balance"
}]
});
};
instead of
displayStart: '100',
I want it be something like:
displayStart: displayStart.displayStart,
But I'm setting the dataSrc to data, which is another branch of the JSON
And here is the JSON data:
{
"displayStart":"100",
"data": [
{
"date":"2015-03-27",
"checknum":null,
"description":null,
"debit":"50.00",
"credit":"0.00",
"balance":"500.00"
},
{
"date":"2015-03-28",
"checknum":null,
"description":null,
"debit":"0.00",
"credit":"250.00",
"balance":"750.00"
}
]
}
I've messed around with the ajax portion using a success/error function, but then it doesn't continue on to finish the table.
How do I set the value?

You can change the page after the data has been loaded by adding two event handlers after you DataTables initialization code as shown below.
// Handles DataTables AJAX request completion event
$('#balance').on('xhr.dt', function( e, settings, json){
$(this).data('is-loaded', true);
});
// Handles DataTables table draw event
$('#balance').on('draw.dt', function (){
if($(this).data('is-loaded')){
$(this).data('is-loaded', false);
var api = $(this).DataTable();
var json = api.ajax.json();
var page_start = json['displayStart'];
// Calculate page number
var page = Math.min(Math.max(0, Math.round(page_start / api.page.len())), api.page.info().pages);
// Set page
api.page(page).draw(false);
}
});

Related

How can I decode JSON Unicode using jQuery in a Select2 dropdown filter

I am using Select2 JS and Datatables JS. The data is in JSON format. The data for one value should display as Animal & Veterinary. In JSON it appears as Animal \u0026amp; Veterinary. The Select2 filter displays it as Animal & Veterinary. How can I add a function to the JS below that will decode the Unicode? Below is a function that can work but I dont know how to add it to the JS below.
var title = 'Animal & Veterinary';
function stringToSlug (title) {
return title.toLowerCase().trim()
.replace(/&/g, 'and')
}
Below is the script. This is where I would like to pass the function into the filter. "select2config"
jQuery( document ).ready( function($) {
'use strict';
// Check condition first if the table class exists then run this init.
if ($('.lcds-datatable--advisory-committee-materials').length > 0) {
let pageClass = function () {
let el = $( 'ul.pagination' ).addClass('pagination-sm');
}
// define order of table's control element
let domStyling = "<'row'<'col-sm-12'lB>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>";
var otable9 = $('table.lcds-datatable--advisory-committee-materials').DataTable( {
// Sort of first date column descending.
order: [[0, 'desc']],
deferRender: true,
deferLoading: 50,
dom: domStyling,
ajax: {
"url": "/datatables-json/advisory-committee-materials-json",
//"url": "/sites/default/files/actest1.json",
"dataSrc": ""
},
processing: true,
columns: [
{ "data": "field_publish_date" }, // publish_date 0
{ "data": "title" }, // node title summary 1
{ "data": "field_site_structure" } // site_structure Committee/Topic 2
],
columnDefs: [
{
"type": "date",
"targets": [ 0 ]
}
],
pageLength: 10,
searching: true,
autoWidth: false,
responsive: true,
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
buttons: [
{
extend: 'excel',
text: 'Export Excel',
exportOptions: {
columns: [ 0, 1, 2 ]
}
}
],
initComplete: pageClass,
drawCallback: pageClass
}); // end datatable
// config and initialize filters
let select2config = {
maximumSelectionLength: 0,
minimumInputLength: 0,
tags: true,
selectOnClose: true,
theme: "bootstrap",
}
let search = $( '#lcds-datatable-filter--search' ).lcdsTableFilter({
table: otable9,
type: 'search'
});
let clear = $( '#lcds-datatable-filter--clear' ).lcdsTableFilter({
table: otable9,
type: 'clear'
});
// wait for ajax call to complete to load column data load
$('table.lcds-datatable--advisory-committee-materials').on( 'init.dt', function() {
let committee = $( '#lcds-datatable-filter--committee-topic' ).lcdsTableFilter({
column: 2,
table: otable9,
select2Options: select2config,
type: 'select',
dataType: 'datatable'
});
})
}}); // end ready function and condition if the table class exists.
I was able to pass in a function to alter the output of JSON so now the filter displays “Animal & Veterinary” not “Animal & Veterinary” By adding this below. The filter now displays Animal & Veterinary but selecting this in the filter does not match the value in the datatable?
let select2config = {
maximumSelectionLength: 0,
minimumInputLength: 0,
tags: true,
selectOnClose: true,
theme: "bootstrap",
escapeMarkup: function (text) { return text; }
}

Binding datasource to Kendo Grid where some field may not be present in JSON

I have a Kendo Grid and the data is bound with results from a webApi. Below is a snapshot of the code. This is used to render the Kendo Grid. Now in the JSON result there could be cases where the field 'nominalVoltage' will not be there. In other words some results may return the field, some may not. In case the field is not returned the code fails. I will get error like field is undefined.
Can this be handled anyway while loading Kendo grid controls?
$scope.columns = [{
field: 'businessCode',
title: 'Business Code',
width: '120px',
}, {
field: 'nominalVoltage',
title: 'Nominal Voltage',
width: '120px'
}];
var options = {
dataSource: {
data: data
},
width: '100%',
resizable: true,
sortable: true,
scrollable: true,
reorderable: true,
dataBinding: function (e) {
var pageSizes = e.sender.dataSource.pageSize() || 20;
},
pageable: {
pageSize: pageSize,
pageSizes: [5, 10, 20, 50, 100, 200],
refresh: true
},
columns: $scope.columns
};
You could apply a conditional template attribute on the grid column which requires validation:
field: 'nominalVoltage',
title: 'Nominal Voltage',
width: '120px',
template: "#if(nominalVoltage) {#:nominalVoltage#} else{'Oops nothing found'}#"
Or the template as a function,
template: validateNominalVoltage
function validateNominalVoltage(dataItem) {
return dataItem.nominalVoltage ? dataItem.nominalVoltage : 'Oops nothing found';
}
Usually this method is used to modify how data is being displayed i.e. bolding content, using an external HTML template but in your case this will work fine for checking if the nominalVoltage attribute contains a value before displaying.
You can set a schema for your data.
schema: {
model: {
businessCode: { type: "string" },
nominalVoltage: { type: "number" },
}
}
You can define template like below
//field: 'nominalVoltage', // do not include it
template: function(data) {
return data.nominalVoltage ? data.nominalVoltage : "";
},
title: 'Nominal Voltage',
width: '120px'

Sending Custom Data from Custom Select field in Datatables

i have created a custom select field into my datatable
html = '<div class="col-md-3"><select id="filterleads" class="filterleads form-control">';
html += '<option value="all">All Leads</option>';
html += '<option value="processed">Processed Leads</option>';
html += '<option value="unprocessed">Unprocessed Leads</option>';
html += '</select></div>';
$("div.toolbar").html(html);
which looks like this
now when the select changes i want it to send its value with the datatable ajax so i can filter records according to that
this is how im doing this
var table = $('#allleadstable').DataTable( {
"processing": true,
"serverSide": true,
"responsive": true,
"iDisplayLength": 50,
"sScrollX": "100%",
"order": [[ 1, "desc" ]],
"sScrollXInner": "100%",
"bScrollCollapse": true,
"ajax": {
url:"/leads",
data: {
"leadfilter": ($("#filterleads").val() ? $("#filterleads").val() : 'all')
}
},
"scrollX":true,
"scrollCollapse": true,
//"sDom": '<"top"flip>rt<"bottom"flip><"clear">',
"dom": '<"toolbar">frtip',
columnDefs: [
{ width: 60, targets: 0 },
{ width: 50, targets: 1 },
{ width: 50, targets: 2 },
{ width: 150, targets: 3 },
{ width: 150, targets: 4 },
{ width: 100, targets: 5 },
//{ width: 100, targets: 7 },
{ width: 100, targets: 6 }
]
});
$(document).on("change", "#filterleads", function(event) {
table.ajax.reload();
});
The problem is that it doesn't find $("#filterleads") and always send the value 'all' even when i change the select
How do I send its value everytime I change select?
The issue is because you only read the value of your select when the page loads, and it's all by default. You need to change your code so that it reads the value of the select when it makes the request. To do this provide a function to the data property:
"ajax": {
url: "/leads",
data: function(data) {
data.leadfilter = $("#filterleads").val()
}
},
Note that I removed the ternary as it's not needed. The select will always have a value.
For more information see the ajax.data entry in the DataTables documentation.
For one dynamic field and 2 static its also may looks like:
ajax: {
url: '/action.php',
data: {
controller: 'someController',
action: 'someAction',
leadfilter: () => $('#filterleads').val()
}
},

Populate JqGrid inside ajax call

I'm trying to populate a JqGrid inside the success function of an Ajax call. My ajax call is passing a date parameter to the function which will filter the results. My grid loads, but no data is displayed and it says Loading... above my grids caption. I'm using a drop down to filter results based on date. My json data has been verified to be valid.
$(document).ready(function () {
$("[name='DDLItems']").change(function () {
var selection = $(this).val();
var dataToSend = {
//holds selected value
idDate: selection
};
$.ajax({
type: "POST",
url: "Invoice/Filter",
data: dataToSend,
success: function (dataJson) {
// alert(JSON.stringify(dataJson));
$("#grid").jqGrid({ //set your grid id
data: dataJson, //insert data from the data object we created above
datatype: json,
mtype: 'GET',
contentType: "application/json; charset=utf-8",
width: 500, //specify width; optional
colNames: ['Invoice_Numbers', 'Amt_Totals','f', 'ff', 't'], //define column names
colModel: [
{ name: 'Invoice_Number', index: 'Invoice_Number', key: true, width: 50 },
{ name: 'Amt_Total', index: 'Amt_Total', width: 50 },
{ name: 'Amt_Due', index: 'Amt_Due', width: 50 },
{ name: 'Amt_Paid', index: 'Amt_Paid', width: 50 },
{ name: 'Due_Date', index: 'Due_Date', width: 50 },
], //define column models
pager: jQuery('#pager'), //set your pager div id
sortname: 'Invoice_Number', //the column according to which data is to be sorted; optional
viewrecords: false, //if true, displays the total number of records, etc. as: "View X to Y out of Z” optional
sortorder: "asc", //sort order; optional
caption: "jqGrid Example", //title of grid
});
},
-- controller
[HttpPost] // Selected DDL value
public JsonResult Filter(int idDate)
{
switch (idDate)
// switch statement goes here
var dataJson = new UserBAL().GetInvoice(date);
return Json(new { agent = dataJson}, JsonRequestBehavior.AllowGet);
Here's the answer if anyone else comes across this. This is what I ended up doing, the rows are getting filtered passed on the date parameter I'm passing to the URL of the function. Having the Grid populate inside the Ajax call also seemed like it was a problem so I had to take it out.
public JsonResult JqGrid(int idDate)
{
switch (idDate)
#region switch date
--Switch Statement--
#endregion
var invoices = new UserBAL().GetInvoice(date);
return Json(invoices, JsonRequestBehavior.AllowGet);
}
[HttpPost] // pretty much does nothing, used as a middle man for ajax call
public JsonResult JqGridz(int idDate)
{
switch (idDate)
#region switch date
--Switch Statement--
#endregion
var invoices = new UserBAL().GetInvoice(date);
return Json(invoices, JsonRequestBehavior.AllowGet);
}
Yes these two functions seem very redundant and they are. I don't know why my post wouldn't update data, but I needed to reload the grid each time and when I did that it would call the first function. So yea the post jqGridz is kinda of just a middle man.
Here's the jquery code I used
var dropdown
var Url = '/Invoice/JqGrid/?idDate=0'
$(document).ready(function () {
$("#jqgrid").jqGrid({
url: Url,
datatype: 'json',
mtype: 'GET', //insert data from the data object we created above
width: 500,
colNames: ['ID','Invoice #', 'Total Amount', 'Amount Due', 'Amount Paid', 'Due Date'], //define column names
colModel: [
{ name: 'InvoiceID', index: 'Invoice_Number', key: true, hidden: true, width: 50, align: 'left' },
{ name: 'Invoice_Number', index: 'Invoice_Number', width: 50, align: 'left'},
{ name: 'Amt_Total', index: 'Amt_Total', width: 50, align: 'left' },
{ name: 'Amt_Due', index: 'Amt_Due', width: 50, align: 'left' },
{ name: 'Amt_Paid', index: 'Amt_Paid', width: 50, align: 'left' },
{ name: 'Due_Date', index: 'Due_Date', formatter: "date", formatoptions: { "srcformat": "Y-m-d", newformat: "m/d/Y" }, width: 50, align: 'left' },
],
pager: jQuery('#pager'),
sortname: 'Invoice_Number',
viewrecords: false,
editable: true,
sortorder: "asc",
caption: "Invoices",
});
$("[name='DDLItems']").change(function () {
var selection = $(this).val();
dropdown = {
//holds selected value
idDate: selection
};
$.ajax({
type: "POST",
url: "Invoice/JqGridz",
data: dropdown,
async: false,
cache: false,
success: function (data) {
$("#jqgrid").setGridParam({ url: Url + selection})
$("#jqgrid").trigger('reloadGrid');
}
})
})
});
Are you actually passing a value to your controller? I see you have data: dataToSend which doesn't match to your controllers idDate.
Is there a reason you are trying to setup your grid this way? Do you not want to deal with paging, or I'm not even sure if your setup would handle rebuild a grid when a user picks the date for a 2nd time.
My personal suggestion would be that you:
setup your grid separately, hidden if you don't want it visible on page load
set it's datatype to local so the grid doesn't load on page load
on the change event:
show the grid
change the postdata parameter the grid has
set the url of the controller/action which will feed the data back to the grid
trigger a grid reload

jquery grid not filled with JSon data

Hi I am not able to get the data from JSON loaded on to grid,
HEre is my code for the grid wich displays the stock prices for the stock for a user :
$(document).ready(function () {
// $("#jQGrid").html("<table id=\"list\"></table><div id=\"page\"></div>");
jQuery("#jqTable").jqGrid({
url:jqDataUrl,
datatype: "json",
mtype: "POST",
height: 250,
// Specify the column names
colNames: ["SYMBOL", "LAST", "CHANGE", "%CHANGE","HIGH/LOW"],
// Configure the columns
colModel: [
{ name: "SYMBOL", index: "SYMBOL", width: 200, align: "left" },
{ name: "LAST", index: "LAST", width: 200, align: "left" },
{ name: "CHANGE", index: "CHANGE", width: 200, align: "left" },
{ name: "%CHANGE", index: "%CHANGE", width: 200, align: "left"},
{ name: "HIGH/LOW", index: "HIGH/LOW", width: 200, align: "left"}
],
jsonReader : {
root: "rows",
page: "page",
total: "total",
records: "records",
cell: "cell",
id: "id",
},
multiselect: false,
// paging: true,
// rowNum:10,
// rowList:[10,20,30],
pager: $("#jqTablePager"),
loadonce:true,
caption: "WatchList"
}).navGrid('#jqTablePager',{edit:false,add:true,del:true});
}
});
But when i try and run the code i am not able to get the contents on to the table (but the grid loads with no content)
And My json is of the form :
{
total: "1",
page: "1",
records: "2",
rows :
[
{id:"1", cell:["cell11", "cell12", "cell13","cell13","cell13"]},
{id:"2", cell:["cell21", "cell22", "cell23","cell13","cell13"]}
]
}
Please help me solve the problem
UPDATE:
I discovered that if you do not put repeatitems:true option into json reader, jqGrid assumes that you are using json dot notation. When you put it into jsonReader, your data is properly loaded. Here is working example: http://jsfiddle.net/a5e5F/3/
Old version:
I played a lot with your jqgrid code, and it seems that there is a bug in this version of jqGrid, which causes your jsonReader not to work. It reads data directly, ignoring root element and assuming that your data is array of json objects in format
{propertyName1:'PropertyValue1', propertyName2:'PropertyValue2', ...}
You can see what I mean on http://jsfiddle.net/a5e5F/2/
If you replace data:rows with data:data (your format of data), it does not load data. Maybe you should try to change your json data to use real json format (with properties named as columns)?
I have been trying a ton of stuff, changing column names to check for issue in #Barmar's coment, which I also thought it is the cause.

Categories