Unable To Display Json Data in html Table Using jquery DataTable - javascript

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

Related

API in javascript is returning data, but is not being saved into an array

I am trying to fetch data from an API of WordPress. Here is my code:
column.data().unique().sort().each(function (d,j) {
var practiceArea = d.practice_area;
var jsonPacticeArea = JSON.stringify(practiceArea);
if (jsonPacticeArea !== undefined) {
var res = $.map(jsonPacticeArea.split("|"), $.trim);
for (var i = 0; i < res.length; i++) {
var str = res[i];
str = str.replace(/"/gi, '').trim();
if (arrayPracticeArea.indexOf(str) === -1) {
arrayPracticeArea.push(str);
}
}
}
});
the "column" is the variable that is getting data through an API, and as far as I do console.log(column. data().unique().sort()), that's returning complete data as you can see in the screenshot:
[![enter image description here][1]][1]
and I want to fetch data is marked in red rectangle and store those values in an array, but as soon as I try to add "each" function to fetch the data and store it in an array (in my case its arrayPracticeArea) its returning undefined values.
Can anyone please help me out? I am just not much experienced with Javascript API.
Here is my AJAX code:
var tableAttorney = $('#table_affliate_attorney').DataTable({
destroy: true,
searching: true,
bLengthChange: false,
scrollX: true,
scrollY: 440,
autoWidth: false,
"language": {
"emptyTable": "We are sorry but there are no Affiliate Attorneys within a 150 mile radius of your requested search"
},
ajax: {
type: 'get',
url: "/wp-admin/admin-ajax.php",
dataType: 'json',
cache: false,
data: {
'action': 'get_attorney_ajax',
'center_lat': center_lat,
'center_long': center_long,
'state': state,
'city': city,
'zip': zip
}
},
columns: [
{"data": "title"},
{"data": "city"},
{"data": "state"},
{"data": "zip"},
{"data": "distance"},
{
"data": "phone",
className: 'datatablePhone',
render: function (data) {
return '' + data + '';
}
},
{
"data": "email",
className: 'px190EM',
render: function (data) {
return '' + data + '';
}
},
{
className: 'js-practice-area',
"data": "practice_area"
},
{
"targets": -1,
"data": 'email',
render: function (data) {
return "<a class='contact-lawyer' href='#' data-toggle='modal' data-target='#exampleModal' data-whatever='#mdo' data-email='"+data+"'>Contact</a>";
}
},
],
columnDefs: [
{"width": "150px", "targets": [0]},
{"width": "130px", "targets": [5]}
],
So I am trying to fetch data from columns->data that has value practice_area.
Here is the fiddle link where I have hosted my whole JS code: https://jsfiddle.net/fareeboy/apor08jn/1/
[1]: https://i.stack.imgur.com/4EOZS.png

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({
...
});

How can i do server side Sorting in JSGrid

I have implemented jsGrid and did the Filtering server side.Now i want to send sorting parameter to server side and do the sorting on server side on the click of column.
This is how i implemented the grid -
var db = {
loadData: function(filter) {
var bFilter = [];
var d = $.Deferred();
console.log("sorting:", filter.sortField, filter.sortOrder);
for (var prop in filter) {
if (prop != "sortField" && prop != "sortOrder") {
bFilter.push({
"Name": prop,
"Value": filter[prop]
})
} else{
var sorting ={ "Name": filter["sortField"], "Type": filter["sortOrder"] };
}
}
$.ajax({
url: "http://abc/abc",
dataType: "json",
data: JSON.stringify({
"filter": bFilter,
"sorting": sorting
})
}).done(function(response) {
d.resolve(response.value);
});
return d.promise();
},
};
$("#jsGrid").jsGrid({
height: 300,
width: "100%",
filtering: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 2,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete the client?",
controller: db,
fields: [{
name: "Name",
type: "text",
width: 150
},
{
name: "Age",
type: "number",
width: 50
},
{
name: "Address",
type: "text",
width: 200
},
{
type: "control"
}
]
});
How would i call the same loaddata method on click of header for sorting to do the filtering and sorting together on server side.
How to disable the client side sorting and do it on serve side same like filtering.
If i set sorting:false it removes the click from the column headers.I want to keep that as well.
I was able to solve this by changing the sort function -
jsGrid.loadStrategies.DirectLoadingStrategy.prototype.sort = function () {
var filters = $("#tableId").jsGrid("getFilter");
var sorting = $("#tableId").jsGrid("getSorting");
this._grid.controller.loadData(filters, sorting);
}

Print Datatables from JS array that is JSON

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>

Telerik Datasource Json Server Paging Not Working

I'm working on a Hybrid app built with Json data. There's a small problem though. I can't figure out how to get the paging to work for the Datasource.
The json structure looks like this.
{
"respond":1,
"paging":{
"stillmore":1,
"perpage":10,
"callpage":1,
"next":2,
"previous":0,
"pages":6,
"result":"52"
},
"message":"",
"result":[
{Main Data}
]
}
Here's my DataSource structure
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "JsonURL",
dataType: "json",
jsonp: "$callback",
cache: true
},
serverFiltering: true,
filter: { logic: "paging", filters: [ { field: "name", operator: "startswith", value: "Jane" } ] },
parameterMap: function (data, type) {
return kendo.stringify(data);
if (type == "read") {
// send take as "$top" and skip as "$skip"
return {
$callpage: data.page,
$perpage: data.pageSize
}
}
}
},
schema: {
data: "result", // twitter's response is { "results": [ /* results */ ] }
total: "paging.result",
},
sort: {
field: "ID",
dir: "desc"
},
serverPaging: true,
serverSorting: true,
pageSize: 20
});
It's not paging. I have about 100 results, and the server only displays 20 every page. When you want to load the next 20, nothing happens. It gets stuck on the loading gif.
I can't seem to figure it out. How can I enable server paging with this Json return?
Any tips would be welcome! Thanks!
You have mistake in your code in:
parameterMap: function (data, type) {
// DELETE THIS LINE: return kendo.stringify(data);
if (type == "read") {
// send take as "$top" and skip as "$skip"
return {
callpage: data.page,
perpage: data.pageSize
}
}
}
You return return kendo.stringify(data); immediately and you can't use your custom binding for page number.
Try to delete this line as I show you above

Categories

Resources