JQuery DataTables Columns Initializing automatically with data - javascript

I have a JQuery DataTable and I have been using it for a while, I guess I am missing something here.
However I came into one of the requirement recently to directly bind with JSON Data.
My JSON for example looks like i.e. coming from API :
[{"componentNumber":"ABC","factory":"India","productNumber":"CR","productRevisionState":"123","placementTimeLocal":"2018-08-21T00:00:00","position":"up"},{"componentNumber":"ABC","factory":"India","productNumber":"CR","productRevisionState":"123","placementTimeLocal":"2018-08-21T00:00:00","position":"up"},
{"componentNumber":"ABC","factory":"India","productNumber":"CR","productRevisionState":"123","placementTimeLocal":"2018-08-21T00:00:00","position":"up"}]
I know that I can use JSON and take columns out in Jquery and pass it to the Datatables columns but what I am looking if there is a simple way where Datatable takes column automatically something like:
$.ajax({
type: "Post",
url: "http://localhost:5555/myapi",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//datasource = data;
$('#myTable').DataTable({
"Data": JSON.parse(data),
"Columns" : JSON.parse(data)
});
},
error: function (err) {
alert(err);
}
})
What I am looking is that:
Does JQuery have any such features or not? If not can you suggest
any other Datatable library which is fast for large dataset.
I want to get rid of all extra looping around the code
I can't update source system from where data is getting returned
Updated Version of Code, took from below answers, thanks Kiran for making me move a bit:
$.ajax({
type: "Post",
url: "http://localhost:5555/myapi",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// **how to get rid of this loop? for looping columns**
var adColumns = [];
$.each(data[0], function (i, item) {
var col = {
data: i,
title: i
};
adColumns.push(col);
})
//datasource = data;
console.log(data);
$('#myTable').DataTable({
"data": data,
"info": true,
"paging": true,
"columns": adColumns
});
},
error: function (err) {
alert(err);
}
})

try the following code. It may help you to achieve the desired result. This may not be an optimized code.
Hope this helps.
EDIT
At least one loop will be required to create the array of column names.So you can also use the following code to eliminate multiple loops.
var adColumns = [];
Object.keys(strData[0]).forEach(key => {
var col = {
data: key,
title: key
};
adColumns.push(col);
});
$(function() {
var strData = [{
"componentNumber": "ABC",
"factory": "India",
"productNumber": "CR",
"productRevisionState": "123",
"placementTimeLocal": "2018-08-21T00:00:00",
"position": "up"
}, {
"componentNumber": "ABC",
"factory": "India",
"productNumber": "CR",
"productRevisionState": "123",
"placementTimeLocal": "2018-08-21T00:00:00",
"position": "up"
},
{
"componentNumber": "ABC",
"factory": "India",
"productNumber": "CR",
"productRevisionState": "123",
"placementTimeLocal": "2018-08-21T00:00:00",
"position": "up"
}
];
/*var dta = strData;
var tableColumnNames = [];
var keys = [];
for (var i in strData) {
var key = i;
var val = strData[i];
for (var j in val) {
var sub_key = j;
keys.push(sub_key);
}
}
var sColumns = Array.from(new Set(keys));
var adColumns = [];
for (var col in sColumns) {
var sKey = sColumns[col];
var col = {
data: sKey,
title: sKey
};
adColumns.push(col);
}*/
var adColumns = [];
Object.keys(strData[0]).forEach(key => {
var col = {
data: key,
title: key
};
adColumns.push(col);
});
$('#myTable').DataTable({
"data": strData,
"columns": JSON.parse(JSON.stringify(adColumns))
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="myTable">
</table>

DataTables has the ability to read data from virtually any JSON data source that can be obtained by Ajax. This can be done, in its most simple form, by setting the ajax option to the address of the JSON data source. See This Link in DataTable Website.
As for your JSON, here is a fiddle

Related

Add data and display into data table in HTML page from web service using AJAX call

I want add and display data into data table plugin from webservice using ajax call,but don't know how to catch data
HTML page:
$(document).ready(function() {
var realPath = "http://localhost:8080";
var webServicePathm = realPath + "/mt/gj/jg?";
//var project = projectname.innerText;
var parmUrl = "tenantid=XYZ";
var webCallUrl = webServicePathm + parmUrl;
var table = $('#example').DataTable({
"ajax": ({
type: "GET",
url: webCallUrl,
data: {},
datatype: 'json',
complete: function(data) {
var objdata = JSON.stringify(data);
},
error: function() {
}
}),
Not sure what exactly you want but try to change code with
$(document).ready(function() {
var realPath = "http://localhost:8080";
var webCallUrl = realPath + "/mt/saasreporting/getopenticketssummary";
//var project = projectname.innerText;
var str = "XYZ";
var var_data = "tenantid="+str;
var table = $('#example').DataTable({
"ajax": ({
type: "POST",
url: webCallUrl,
data: var_data,
datatype: 'json',
complete: function(data) {
var objdata = JSON.stringify(data);
},
error: function() {
}
}),
In the main documentation of DataTable, you need to pass the object that contains the json to the ajax attribute. Here is the example:
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "data/arrays.txt"
} );
} );
Where data that is send to ajax:
{
"data": [
[
"Donna Snider",
"Customer Support",
"New York",
"4226",
"2011/01/25",
"$112,000"
]
]
}
Here is link to the official documentation.

BS Typeahead doesn't show results

i have this problem with Bootstrap Typeahead.
HTML Markup:
<div class="form-group">
<label for="">Recipients</label>
<input id="recipients" name="recipients"
autocomplete="off"
class="form-control"
data-role="tagsinput">
</div>
JavaScript:
$('#recipients').tagsinput({
allowDuplicates: false,
trimValue: true,
confirmKeys: [13, 44],
typeahead: {
source: function(queryForHints) {
if (queryForHints.length < 4)
return '';
var parameters = {
'queryForHints': queryForHints
};
jQuery.ajax({
url: "/xxxx/xxxx",
data: parameters,
type: "POST",
dataType: "json",
success: function(data) {
return (data);
},
error: function(data) {
console.log("error for xxxxx/xxxxx");
},
async: true
});
}
}
});
After Ajax call I get this array:
[{
"value": "+393334029137",
"text": "Dean Leandra (+393334029137)"
}, {
"value": "+393333419836",
"text": "Alfonso Erasmus (+393333419836)"
}, {
"value": "+393173833341",
"text": "Travis Aquila (+393173833341)"
}, {
"value": "+393334998841",
"text": "Conan Preston (+393334998841)"
}]
The problem is: I see nothing :( nothing appears. typeahead doesn't work.
In the console, I get this error
bootstrap-tagsinput.js:331 Uncaught TypeError: Cannot read property
'success' of undefined
Can you help me solve this?
success: function(data) {
var sourceData = [];
for (var i = 0; i < data.length; i++) {
sourceData.push(data[i].text);
}
return (sourceData);
What you have from your JSON response is an object array. You want to see text as a suggestion I assumed. So you need to get text from your object because typeahead source expects a string array. Push text values into another string array and return it. I haven't tested the code yet but it should work for you.
Another issue you have is that you are making an AJAX call which is async. That's why you have undefined from success.

Parse Json data in Jquery

I am new to Jquery, Ajax and JSON.
I am facing issue with the parsing of Json data.
I have been through many questions on stackoverflow
Parsing JSON objects for HTML table
Access / process (nested) objects, arrays or JSON
Parse JSON in JavaScript?
How could I parse through this JSON object in JQuery?
and many more...
Still I am not able to parse the Json data.
My Jquery Looks like :
$.ajax({
/* type : "POST", */
url : "launchapptest",
/* contentType: "application/json; charset=utf-8", */
data : "processDateInput="+processDate,
dataType : "json",
async: true,
success : function(result) {
var od = JSON.stringify(result) ;
var obj = JSON.parse(od);
console.log(obj.od);
console.log(obj.od.percentageCompleted);
console.log(od);
$.each(JSON.parse(od), function(idx, obj) {
console.log(obj.tagName);
});
}
});
I have tried all the combinations to parse this data, but the js console print as "undefined"
I am able to print the json object as :
{
"od": [
{
"dateProcessed": [
"09/11/2014",
"10/11/2014",
"11/11/2014",
"12/11/2014"
],
"percentageCompleted": 25,
"processRunning": 0,
"remainingTime": 0,
"successBatchCount": 0,
"totalBatchCount": 0
}
],
"processDateInput": "12/11/2014"
}
Please help me how can I fetch dateProcessed array and percentage complete.
Try this code.
$.ajax({
/* type : "POST", */
url: "launchapptest",
/* contentType: "application/json; charset=utf-8", */
data: "processDateInput=" + processDate,
dataType: "json",
async: true,
success: function (result) {
var od = JSON.stringify(result);
var obj = JSON.parse(od);
$.each(obj, function (index, value) {
console.log(obj[index][0].percentageCompleted);
console.log(obj[index][0].processRunning);
console.log(obj[index][0].remainingTime);
console.log(obj[index][0].successBatchCount);
console.log(obj[index][0].totalBatchCount);
console.log(obj.processDateInput);
$.each(obj[index][0].dateProcessed, function (ind, val) {
console.log(val);
})
});
}
});
When you specify the dataType as JSON, jQuery will automatically parse it for you. Parsing it again as you are (multiple times, even) will cause issues. Try this:
success: function(result) {
console.log(result.od);
console.log(result.od[0].percentageCompleted);
}
I'm not entirely sure what your $.each loop is trying to do as there is no tagName property in your object.
What is the is the return data of your AJAX call
is like this then
{
"od": [
{
"dateProcessed": [
"09/11/2014",
"09/12/2014"
],
"percentageCompleted": 25,
"processRunning": 0,
"successBatchCount": 0,
"totalBatchCount": 0
}
],
"processDateInput": "12/11/2014"
}
you can parse it like this
var json = JSON.parse(result);
var od = json['od'];
var processDateInput = json['processDateInput'];
$.each(od, function(index, value){
console.log(value, index);
});
hope it would work on you.
no need of parsing it because you have already mentioned it as json you can simply do like this:
success: function(result) {
console.log(result.od);
console.log(result.od[0].percentageCompleted);
console.log(od);
$.each(result, function(idx, obj) {
console.log(obj[0].dateProcessed);
});
}

jsTree - Populate Tree Dynamically using AJAX/C#Web Method

I have a div which I would like to fill with a jsTree:
I get the "Loading" icon where the tree is meant to display, however, there would seem to be a javascript error, even though one is not thrown.
I load my folder structure from an AJAX Request as follows. The Documents.aspx/GetFolders Web Method returns a List containing FolderId, ParentId & Folder Name. I have debugged the web method and it is passing the correct results to the jsTree "data" function.
$.ajax({
type: "POST",
url: 'Documents.aspx/GetFolders',
contentType: "application/json; charset=utf-8",
success: function (data) {
data = data.d;
$("#tree").jstree({
"core": {
"themes": {
"responsive": true
},
"data": function () {
var items = [];
items.push({ 'id': "jstree_0", 'parent': "#", 'text': "Documents" });
$(data).each(function () {
items.push({ 'id': "jstree_" + this.DocumentFolderId, 'parent': "jstree_" + this.ParentId, 'text': "" + this.Name });
});
return items;
}
},
"types": {
"default": {
"icon": "fa fa-folder icon-lg"
},
},
"plugins": ["contextmenu", "dnd", "state", "types"]
});
},
error: function () {
toastr.error('Error', 'Failed to load folders<span class=\"errorText\"><br/>There was a fatal error. Please contact support</span>');
}
});
After debugging the code, it seems the data is being retrieved correctly and is returning the object array as intended.
Is there are any problem with the above (or is there somewhere else I should be looking)? Or is there a better method of achieving its intended purpose?
I think I have finally found the answer! :)
"core": {
"themes": {
"responsive": true
},
"data": {
type: "POST",
url: "Documents.aspx/GetFolders",
contentType: "application/json; charset=utf-8",
success: function (data) {
data.d;
$(data).each(function () {
return { "id": this.id };
});
}
},
}
Server side, you need to return the data in the array format required, i.e:
[{id = "node0", parent = "#", text = "Documents"},
{id = "node1", parent = "node0", text = "Public"},
{id = "node2", parent = "node0", text = "Restricted"}]
Just in case anyone has the "loading..." issue, this format fixed it for me when returning data.
[{"id":"node0", "parent":"#", "text":"Documents"},
{"id":"node1", "parent":"node0", "text":"Public"},
{"id":"node2", "parent":"node0", "text":"Public"}]

JQPlot, JSON and 'No data specified' Error

I am trying to use JQPlot within a VB.NET application under .NET 3.5. On a button click, using jquery, I am trying to populate the JQPlot Chart with JSON derived data using a ASP.NET Webservices Source file (which is part of the solution).
The JSON data is sent by the web service but when it is presented to JQPlot I get the javascript error 'No Data Specified' which is generated by JQPlot code.
My code listing is as follows:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
Javascript code outside the 'document.ready' function:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
//url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
var ret = response.d;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
return ret;
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var jsonurl = "./jsondata.txt";
function getElectricDataJSON() {
var ret = ajaxDataRenderer();
var plot1 = $.jqplot('chart2', jsonurl, {
title: "AJAX JSON Data Renderer",
dataRenderer: ret, //$.jqplot.ciParser
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
}
The JSON data format is as follows:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220429.41 }, ... ]
Any help or advice will be appreciated.
Thanks to #Fresh for their quick response. Here is the complete solution to my problem:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
JS function to get the data from a web service:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
ret = response.d; // return response string object
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
Data structure outputted by the web service is:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7,095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1,137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220,429.41 }, ... ]
Data structure that is expected by JQPlot:
[ [ "2013-09-23T00:00:00", 7095.65 ] , [ "2013-08-22T00:00:00", 1137.96 ], [ "2013-07-24T00:00:00", 220429.41 ], ... ]
Note the removal of the comma's in the 'expected data' Bill field.
And finally, the function getElectricDataJSON() that is being called by btnASMX1 where 'chart2' is the ID of the div tags where the chart will be drawn.
function getElectricDataJSON() {
// Get JSON 'string' object
var ret = ajaxDataRenderer();
// If JSON string object is null, stop processing with friendly message
if (ret == null) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>CHARTS ARE NOT AVAILABLE AT THIS TIME</div>");
return false;
}
// Now push required data into a JSON array object
var sampleData = [], item;
$.each(ret, function (key, value) {
sampleData.push([value.todate, parseFloat(value.Bill.replace(/,/g, ""))]);
});
var plot = $.jqplot('chart2', [sampleData], {
title: 'AJAX JSON Data Renderer',
dataRenderer: sampleData,
...
});
}
The method signature for your datarender (i.e. ajaxDataRender) is wrong. The signature should look like this:
function(userData, plotObject, options) { ... return data; }
(See the documentation here)
In your example you are passing the datarenderer "ret" which is not a function with the correct datarender signature. Also the jsonurl you are passing to getElectricDataJSON() is redundant as at no point in your code is the data from "AccountsService.asmx/GetJSONData" persisted to "./jsondata.txt".
Hence you should change your code to this:
$(document).ready(function(){
function ajaxDataRenderer(url, plot, options) {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
url: url,
dataType: "json",
success: function (response) {
var ret = response;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var url = "AccountsService.asmx/GetJSONData";
function getElectricDataJSON() {
var plot1 = $.jqplot('chart2', url, {
title: "AJAX JSON Data Renderer",
dataRenderer: ajaxDataRenderer,
});
}

Categories