Print Datatables from JS array that is JSON - javascript

I got a JS var JSONarray that is initialized by PHP script that assign it a JSON value. I tried to use DataTables to format data and print it in readable form, but i cannot manage it to work.
PHP code is working fine and I tried the data samples from DataTables site and it worked but with this JSON it is not working.
Here are my codes:
JSONarray
var JSONarray = [{
"id": "ffd60d8e-4b2d-a693-bfcc-5959e202caa3",
"nr_faktury": "FV\/45654fgh\/fh231",
"nazwa_klienta": "klient3",
"kwota": "6045.00"
}];
JS
$(function() {
$('#example').DataTable( {
"ajax": JSONarray,
columns: [
{ title: "id" },
{ title: "nr_faktury" },
{ title: "nazwa_klienta" },
{ title: "kwota" }
]
} );
});

You can change the data source definition to use data instead of ajax since there's no Ajax call involved - you are writing out the JSONArray directly into the response when you load the page. You will also need to add a data property to the columns array. See full script below:
var JSONarray = [{
"id": "ffd60d8e-4b2d-a693-bfcc-5959e202caa3",
"nr_faktury": "FV\/45654fgh\/fh231",
"nazwa_klienta": "klient3",
"kwota": "6045.00"
}];
$(document).ready(function(){
$('#example').DataTable({
data: JSONarray, //Replace JSONarray with data source URL
columns: [
{ data: "id", title:"id" },
{ data: "nr_faktury", title: "nr_faktury" },
{ data: "nazwa_klienta", title:"nazwa_klienta" },
{ data: "kwota", title:"kwota" }
]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<table id='example'></table>

var JSONarray = [{
"id": "ffd60d8e-4b2d-a693-bfcc-5959e202caa3",
"nr_faktury": "FV\/45654fgh\/fh231",
"nazwa_klienta": "klient3",
"kwota": "6045.00"
}];
$(document).ready(function(){
$('#example').DataTable({
"ajax": JSONarray, //Replace JSONarray with data source URL
columns: [
{ title: "id" },
{ title: "nr_faktury" },
{ title: "nazwa_klienta" },
{ title: "kwota" }
]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<table id='example'></table>

Related

Unable To Display Json Data in html Table Using jquery DataTable

i have C# function That Return Me Json Formated Data , function is below
void DisplayProjectMasterList()
{
string JSONString = "";
DataTable Dt = DB.GetDataTable("Sp_GetProjectMasterList");
if (Dt.Rows.Count > 0)
{
JSONString = JsonConvert.SerializeObject(Dt);
}
Context.Response.Write(JSONString);
}
and I am Calling This Function Via Ajax .in console i am getting json data But i dont know how to pass it to Jquery data table to display.. below is the javascript function... please help Me
function DisplayProjectMasterList() {
$.ajax({
url: 'project-master.ashx',
type: "POST",
dataType: 'json',
data: {
'fun': 'DisplayProjectMasterList'
},
success: function (data) {
console.log(data);
if (Chk_Res(data.errorMessage) == false) {
$('#tbl').dataTable({
paging: true,
sort: true,
searching: true,
scrollY: 200,
data: data,
columns: [
{ 'data':data.Prj_Id },
{ 'data':data.Prj_No },
{ 'data':data.Prj_Name },
{ 'data':data.Cus_Company_Name },
{ 'data':data.Prj_StartDate },
{ 'data':data.Prj_CompletionDate },
]
});
}
}
});
}
i am Getting FOllowing error while doing So:
DataTables warning: table id=tbl - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
Hi make sure the data you are being returned is in the following format:
{
"data": [
{
"Prj_Id": 1,
"Prj_No": 1,
"Prj_Name": "name",
"Cus_Company_Name": "company",
"Prj_StartDate": "2011/04/25",
"Prj_CompletionDate": "2011/04/25"
},
{
"Prj_Id": 1,
"Prj_No": 1,
"Prj_Name": "name",
"Cus_Company_Name": "company",
"Prj_StartDate": "2011/04/25",
"Prj_CompletionDate": "2011/04/25"
}
]
}
jquery Datatables by default looks for data property for the array of objects
https://datatables.net/reference/option/ajax.dataSrc
https://datatables.net/examples/ajax/objects.html

Trying to access dataTable variable outside ajax is giving undefined

I have a jquery autocomplete that once a value is selected it loads a datatable with checkbox from an ajax call. Then while submitting the form I need to access the datatable variable to iterate each row to get the selected ones, but the datatable variable appears as undefined.
I'm doing the same as in this example, only difference is the data is coming from an Ajax request.
Can you please help me understand why is that happening?
$(document).ready(function() {
var campId;
var t_OmnitureCode;
// Campaign input autocomplete
$("#campaign").autocomplete({
source: function(request, response) {
$.ajax({
url: "promotion",
type: "GET",
data: {
term: request.term,
action: "searchCampaign"
},
dataType: "json",
success: function(data) {
if (!data.length) {
var result = [{
label: "no match found",
value: "-1"
}];
response(result);
} else {
response($.map(data, function(item) {
return {
label: item.name,
value: item.campaignId
}
}));
}
}
});
},
select: function(event, ui) {
event.preventDefault();
campId = ui.item.value;
if (campId != "-1") {
this.value = ui.item.label;
// This will apply datatables getting the content from an Ajax call
t_OmnitureCode = applyDataTableOmnitureCode(campId);
}
},
focus: function(event, ui) {
event.preventDefault();
this.value = ui.item.label;
}
});
// Handling form submission
$("#frm_promotion").on("submit", function(e) {
var form = this;
// Variable for datatable "t_OmnitureCode" is undefined below
var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
EDIT:
Just realized that even while assigning the variable (t_OmnitureCode = applyDataTableOmnitureCode(campId);) it is undefined, not sure why.
Here is the applyDataTableOmnitureCode code:
function applyDataTableOmnitureCode(campId) {
$("#tbl_omnitureCode").DataTable({
destroy: true,
scrollX: true,
fixedColumns: {
leftColumns: 1
},
"ajax": {
"url": "promotion",
"type": "GET",
"data": {
action: "searchOmnitureCodesByCampaignId",
campaignId: campId
},
"dataSrc": ""
},
"columns": [
{ "data": "key" },
{ "data": "omnitureCode" },
{ "data": "urlAppName" },
{ "data": "language" },
{ "data": "channel" },
{ "data": "createDateTime", "defaultContent": "" },
{ "data": "updateDateTime", "defaultContent": "" }
],
"columnDefs": [
{ "targets": 0, "checkboxes": { "selectRow": true } }
],
"select": {
"style": "multi"
},
"order": [[1, "asc"]],
"fnInitComplete": function() {
$("#omnitureCodeSection").show();
}
});
};
You may need to grab your DataTables object into a variable before using that:
var t_OmnitureCode = $("#tbl_omnitureCode").DataTable();
var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
And, by the way, your method of populating DataTable with external ajax-call is suboptimal. There's an ajax option for that purpose where you can specify all the necessary parameters and get better integration with DataTables API and better performance (as you don't really need to destroy and create your DataTable upon each refresh).
You would simply need to trigger .ajax.reload() whenever you need to refresh your table data.
It's a matter of scope : You declare the variable table inside $(document).ready function.
You may want to put it outside in the global scope :
var table;
$(document).ready(function() {
table = $('#example').DataTable({
...
});

Kendo Grid: populating with data from ajax

I'm trying to populate a kendo grid with data retrieved via ajax. Here is the ajax:
var model = #Html.Raw(Json.Serialize(Model));
$(document).ready(function () {
$.ajax({
url: "/Utilities/Report/Run",
data: JSON.stringify(model),
contentType: "application/json",
type: "POST",
success: function(result) {
var ds = new kendo.data.DataSource({
data: result
});
alert(result);
$("#grid").data("kendoGrid").setDataSource(ds);
},
error: function(result) {
options.error(result);
}
});
$("#grid").kendoGrid({
toolbar: ["excel", "pdf"],
excel: {
fileName: "test"
},
pdf: {
fileName: "test"
},
});
});
At the alert(result) this is what the data looks like:
[
{"TEST":"one"},
{"TEST":"two"},
{"TEST":"three"}
]
The ajax call appears to be working and the data looks good to me, but the kendo grid is not updating, it remains blank. I also do not get any error. I've tried placing the kendoGrid inside the ajax success function with the same result. I've tried using transport and read in the DataSource to retrieve the data but that kept giving me an error: n.slice is not a function. However, others seemed to think that was because there was no schema defined. Due to the kind of data I am retrieving, I cannot define this. The data retrieved from the server could have any column/field names, and any number of columns. It is not complex JSON however.
How do I get my grid to populate with this data?
I have created a new Datasource and mapped it to the existing one outside the success method.
Can you try this one below :
var newDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/Utilities/Report/Run",
dataType: "json",
data: JSON.stringify(model),
error: function (result) {
options.error(result);
}
}
}
});
var d1 = $("#grid").data("kendoGrid");
d1.dataSource.data([]);
d1.setDataSource(newDataSource );
make changes as per your necessity if I have missed any . Kendo data binding is always confusing :D
Kendo DataSource is very powerful. Ideally, you do not need to make a manual Ajax call. Instead, DataSource can Ajax request data from URL by itself, if Grid needs data.
https://jsfiddle.net/6gxqsrzu/
$(function() {
var dataSource = new kendo.data.DataSource({
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: {
type: "number"
},
Freight: {
type: "number"
},
ShipName: {
type: "string"
},
OrderDate: {
type: "date"
},
ShipCity: {
type: "string"
}
}
}
},
serverPaging: true,
pageSize: 5,
serverSorting: true,
sort: {
field: 'OrderDate',
dir: 'asc'
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
sortable: true,
pageable: true,
columns: [{
field: "OrderID",
filterable: false
},
"Freight", {
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
}, {
field: "ShipName",
title: "Ship Name"
}, {
field: "ShipCity",
title: "Ship City"
}
]
});
});
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.material.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/kendo.all.min.js"></script>
<div id="grid"></div>

TypeError: c is undefined while saving a new entry using New Entry Form in DataTable

I have this table that displays a bootstrap modal with a form inside, when i fill this form and save my data or clicking to close modal, i want to refresh the data table but this caught and error:
TypeError: c is undefined
...dErrors";g[w0]("postSubmit",[c,n,j]);if(!c.error)c.error="";if(!c[(j4a+R6a+K8+i1...
on line 296 in dataTables.editor.min.js
this show this error when i refresh the ajax data, this is my code:
var editor;
var oTable;
function getStudentdetails(id) {
editor = new $.fn.dataTable.Editor({
dom: "Tfrtip",
table: "#table_student_details",
fields: [ {
label: "Id:",
name: "id",
attr: {
maxlength: 50,
name:"id",
placeholder: 'ID'
}
}, {
label: "Name:",
name: "name"
}
],
ajaxUrl: {
"create": "/addStudentdetails",
"edit": "/editStudentdetails",
"remove": "/deleteStudentdetails"
},
});
oTable = $('#table_student_details').DataTable({
dom: "Tfrtip",
destroy: true,
ajax: {
"url": url_prefix + "/getStudentDetails",
"data": function(d) {
d.id = id;
}
},
tableTools: {
sRowSelect: "os",
aButtons: [{
sExtends: "editor_create",
editor: editor
}, {
sExtends: "editor_edit",
editor: editor
}, {
sExtends: "editor_remove",
editor: editor
}]
}
});
}
I use the Files and versions and also in the below order:
jquery-1.11.1.min.js
jquery.dataTables.min.js-> 1.10.2
dataTables.bootstrap.js
dataTables.tableTools.min.js-->2.2.2
dataTables.editor.min.js ->1.3.2
Somebody help me pls.For helpers reference I have put my javascript files in here http://jsfiddle.net/Lujjz9ag/1/
Even I was getting the same error when I was using column filter
TypeError: c is undefined
...dErrors";gw0;if(!c.error)c.error="";if(!c[(j4a+R6a+K8+i1...
and I realized this was happening only when there was a empty data response
The response looked like this
{"iTotalRecords":0,"iTotalDisplayRecords":0,"aaData":NULL}
Here you can see the aaData is NULL. the datatable always looks for an array in response and checks the length, which throws error.
So I converted aaData to array if it is empty and it got fixed.
{"iTotalRecords":0,"iTotalDisplayRecords":0,"aaData":[]}

Populating A Kendo UI Grid With A JSON String

I'm using a Kendo UI Grid and can't get it to show data when using a JSON string. I created a fiddle here. What am I doing wrong?
<script type="text/javascript">
$(document).ready(function ()
{
$('#grid').kendoGrid(
{
scrollable: false,
data: '{"TestHeader":"This is some test data"}',
columns: [ { field: 'TestHeader' } ]
});
});
</script>
<div id="grid"></div>
This might be closer to what you want (note the changes to the data definition):
$(document).ready(function ()
{
$('#grid').kendoGrid(
{
scrollable: false,
dataSource: { data: [ { "TestHeader": "This is some test data"} ] },
columns: [ { field: 'TestHeader' } ]
});
});​

Categories

Resources