Parsing LocalDate and list of nested objects in ajax response - javascript

Can anyone help me please .
I am trying to get solution to two problems. First, how to display LocalDate in ajax response. 2nd, iterating over list of Custom objects received in ajax response.
I am passing List of Custom Object and localDate in ajax response and not sure how to display it in UI. date filed is displaying [object object]. Below is my ajax call code.
var table = $("#example").DataTable( {
"bProcessing": true,
"bServerSide": true,
'sDom' : 'T<"clear">lrtip',
"sort": "position",
"sAjaxSource": "springPaginationDataTables.web",
"aoColumns": [
{ "mData": "name" },
{ "mData": "position" },
{ "mData": "office" },
{ "mData": "phone" },
{ "mData": "start_date" },
{ "mData": "salary" },
{ "mData": "dob" },//LocalDate
{ "mData": "addresses" },//list of addresses
],
columnDefs: [
{
targets: [ 6 ],
render: function ( data, type, row ) {
console.log(type);
return data;//process LocalDate here
}
},
{targets: [ 7 ],
render: function ( data, type, row ) {
console.log(type);
return data;//process addresses list here
}
}
]
} );
From MVC Controller I am passing list Of persons into JSON object as below
PersonJsonObject personJsonObject = new PersonJsonObject();
//Set Total display record
personJsonObject.setiTotalDisplayRecords(500);
//Set Total record
personJsonObject.setiTotalRecords(500);
personJsonObject.setAaData(personsList);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json2 = gson.toJson(personJsonObject);
return json2;
PersonJsonObject is Jquery Datatable kind of object which holds records track and list of data to be displayed on UI.
Person object has list of address Object. How do iterate over list after getting list say data.getaddresses and store this in variable. I know how do we iterate over list using jsp tags but not sure how to do same in Jquery

Its solved. For LocalDate issue, custom Module needs to be registered. Check this link for details.
Ajax response does not parse LocalDate
For iterating over list, use simple jquery foreach loop
$j.each(data, function (index, value) {
var temp = value.field1+" "+value.field1+" ";//field1 and field2 are fields of custom object
console.log(temp);
return temp;
});

Related

Server side pagination in KTDatatable (Metronic)

I am new to KTDatatable in Metronic.
I am trying to use server side pagination in Metronic dashboard, and I am parsing the data in a KTDatatable, but I can't find a way to parse the returned data from the API and to view number of pages and each page URL.
The code that I was able to write so far is:
data: {
type: 'remote',
source: {
read: {
url: dataURL,
method: 'GET',
contentType: 'application/json',
map: function(data) {
var cards = data.cards.data;
var currentPage = data.cards.current_page;
var lastPage = data.cards.last_page;
return cards;
}
},
},
pageSize: 10,
serverPaging: true,
},
In this code I was able to get the first ten records but:
1- I wasn't able to parse them the way I want in the table.
2- I wasn't able to show the pages number nor calling the API for the second page or the (x) page I want.
These are the things I want to do.
Thanks in advance.
You can go back to the end of the KT-Datatable documentation to find most of answers you want KT-Datable documentation, but I am gonna explain more hoping it will be more clear.
So the returned value from the API (Json) should look have two main objects meta and data, and it looks something like this:
{
"meta": {
"sort": "desc",
"field": "IssueName",
"page": 1,
"pages": 2,
"perpage": "10",
"total": 11
},
"data": [
{
"IssueName": "******",
"CardNumber": "******"
},
{
"IssueName": "******",
"CardNumber": "******"
}
]
}
And after getting the values of the response from the API you should only return the data object to be parsed by the datatable so the map function should look something like this:
map: function(data) {
return data.data;
}
and it will process the meta data itself.
To parse the data into the columns you should use the same key name of the data in column definition array, so in my example I used it like this:
columns: [
{
field: 'IssueName',
title: columnsTitles.issue,
type: 'string',
},
{
field: 'CardNumber',
title: columnsTitles.card_number,
type: 'string',
},
]
And every time the datatable calls the API it will send more data that will help you give the right response, the data will be on a shape of an array (The field name should be the same as the key):
[
"pagination" => array:4 [
"page" => "1"
"pages" => "2"
"perpage" => "10"
"total" => "11"
],
"sort" => array:2 [
"field" => "IssueName"
"sort" => "desc"
],
]
The sent data is related with the pagination and sorting type you have to get from the API, and you can also add filters and they will be stored in the array in the "query" field, and you can handle them in the backend.

JS datatabe with Array edit

I has create HTML page, with user entry data in page then upload to SQL server.
I has study DataTable to load array to table, try edit still not , has any one can help?
var array = ['54 GR', '89 GR', 'Internal Transfer', 'Putaway']
$('#example').DataTable({
data: array,
"searching": false,
columns: [{
"data": 0,
"title": "Date"
}, {
"data": 1,
"title": "Account"
}, {
"data": 2,
"title": "Type"
}, {
"data": 3,
"title": "OPDeployed",
"render": function(data, type, row, meta) {
return "<input type='text' value=''/>";
}
}]
});
Its really difficult to say without being able to see the page or even the code. All I can really say is that the load order should be:
jQuery
jQuery UI
DataTables
2 and 3 can be swapped and you shouldn't load more than one of each.

How to get a specific or multiple values (or keys) from nested JSON

I have a (nested) data structure containing objects and arrays. How can I extract the information, i.e. access a specific or multiple values (or keys)?
{
"data": [{
"name": "name1",
"value": "value1",
"list": [{
"sname": "sname1",
"svalue": "svalue1"
}, {
"sname": "sname2",
"svalue": "svalue2"
}]
}]
}
jQuery
var pk = $("#pk").val();
console.log(pk);
url = "/register/search?id=" + pk;
console.log(url);
$('#largeTable').DataTable({
"ajax": url,
"bDestroy": true,
"columns": [{
"data": "name"
},
{
"data": "value"
},
{
"data": "list.1.sname"
},
{
"data": "list.1.svalue"
},
{
"data": null,
"defaultContent": editview
}
]
});
Here it is possible to display either first or second list values by using list.1 or list.0
But I want two values at a time.
Also, how could I access the svalue of the second item in list?
I tried with data.list[1] but:
TypeError: data.list is undefined
Since data is an array, you should first get the item - and since you only have one item - you'd use data[0], and then get access to the list property like data[0].list[1] - this will give you the second item in the list - but since you are interested in a specific property (svalue) of this item, you will then access it like this: data[0].list[1].svalue.
A better approach would be to loop through the items in the data array - and then for each item, loop through the items in the list array. See #Rajesh's comment.
I hope that helps;
Specifically you can access it like this object.data[0].list[1].svalue. The reason data.list is undefined is because data corresponds to an array data: [{ }] this is why we use data[0], but data itself is a key in an object so before you can get to data you need to access it. If the objects name where data resides were object (like I did below) then it'd be accessed like this object.data[0]
const object = {
"data": [{
"name": "name1",
"value": "value1",
"list": [{
"sname": "sname1",
"svalue": "svalue1"
}, {
"sname": "sname2",
"svalue": "svalue2"
}]
}]
}
console.log(object.data[0].list[1].svalue)

DataTables - Format returning ajax data

I am working on this example from DataTables.net but I have made modification so that it works with my ajax call to my API.
My problem is that my API returns the DateTime values like this...
Created=2015-02-13T00:00:00
I need to be able to convert that to just be just the date without the time for my table (hopefully without changing the API). I have tried everything that I know to try. I am still sort of a beginner at this advanced javascript stuff. I was trying to do just a simple substring but I dont think that is working. Well at least how I was trying anyways.
Thanks for anything help!
DataTables v1.10.5
Jquery v1.11.2 (due to need to support IE8)
Original Problem Code:
$(document).ready(function () {
var table = $('#AllHuddleRecords').DataTable({
"ajax": "../api/huddle/posts",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data" : "EmpName" },
{ "data": "Created" },
{ "data" : "PriorityName" },
{ "data" : "TopicName" }
]
});
Thanks to the guidance of cmxl...here is the working code...
var table = $('#AllHuddleRecords').DataTable({
"ajax": "../api/huddle/posts",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data" : "EmpName" },
{ "data": "Created" },
{ "data" : "PriorityName" },
{ "data" : "TopicName" }
],
"columnDefs": [
{
"render" : function (data, type, row) {
return new Date(data).toLocaleString();
},
"targets": 2
}
]
});
You can hook in to the column rendering event. See the documentation here:
https://datatables.net/examples/advanced_init/column_render.html
$(document).ready(function() {
$('#example').dataTable( {
"columnDefs": [
{
// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
// this case `data: 0`.
"render": function ( data, type, row ) {
return data.slice(0, data.indexOf('T'));
},
"targets": 0
},
{ "visible": false, "targets": [ 3 ] }
]
} );
} );
Or if you want to parse the string as a date you can refer to this answer here:
Converting string to date in js
//...
"render": function ( data, type, row ) {
return new Date(data).toString();
}
//...
Here you can look even deeper into the Date object in Javascript:
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date
Is it possible to do some pre-processing on your data before you send it to data tables, for example if you are inserting the following data into your data table, use Date.parse() on each element of your data to convert to the desired format?
var ajaxData = {
"data": [{
"EmpName": "Bob",
"Created": "2015-02-13T00:00:00",
"PriorityName": "Priority1",
"TopicName": "Topic1"
}]
};
$(ajaxData.data).each(function() {
var dateMillis = new Date(this.Created);
this.Created = dateMillis.getMonth() + "/" + dateMillis.getDay() + "/" + dateMillis.getFullYear();
});
Note that if you want to sort on your date column, then the solution may well be to pre-process data and convert dates to milliseconds using Date.parse() and then use render to convert the date to readable format as cmxl suggested. Good luck!

Dynamically creating nodes in a jstree tree structure

I have to retrieve a list of menu item from a database and display it in a tree structure I want to use the menu name as the node name and menu id as the id of the node.
The method I used was to retrieve the data using an ajax call and put them into a list and then display it as a tree.But I think dynamically creating nodes depending on the data is more efficient.
function createNodeList(){
$('#menuCPanel #contentData #tree').jstree({
"json_data" : {
/*"data" : [{
"data" : {title : "menuName"},
"attr" : {id : "menuId"},
"state" : "closed"
}
],*/
"ajax" :{
"type" : "POST",
"url" : "?m=admin?action=getNodeList",
"dataType" : "json",
"data" : function(result){
return {
id : result.attr ? result.attr("id") : result['menuId'],
title : result.attr ? result.attr("title") : result['menuName']
};
},
},
},
"callback" : {
},
"themes" : {
"theme" : "classic",
"dots" : true,
"icons" : true
},
"plugins" : ["json_data", "themes"]
}).bind("select_node.jstree", function (e, data) { alert(jQuery.data(data.rslt.obj[0], "jstree").id) });
}
}
this is the stucture of my json data
"data":[{"menuId":"1","menuName":"Top Menu"},{"menuId":"2","menuName":"Main Menu"},{"menuId":"3","menuName":"Bottom Menu"},{"menuId":"4","menuName":"Main Menu"}]}
I would like to know what is wrong with the above result and how to dynamically create a node within in the ajax.success();
I went through some examples but all of them use the jstree.cretate() which i can't invoke inside jstree.json_data.ajax.success()
thanks in advance :)
This is a standard jstree with json data, which also binds select_node to do actions when a node is selected. Nodes must not have an ID which are plain numbers or contain jquery special selector characters. Number IDs must have a standard character first. so 1 should be N1, 2 should be N2 for example.
$('#MyTreeDiv').jstree({
"json_data": {
"ajax": {
"type": "POST",
"url": "/MyServerPage.aspx?Action=GetNodes",
"data": function (n) { return { id: n.attr ? n.attr("id") : 0} },
}
},
"themes": {
"theme": "default",
"url": "/Content/Styles/JSTree.css",
"dots": false
},
"plugins": ["themes", "json_data", "ui", "crrm"]
}).bind("select_node.jstree", function (e, data) {
var selectedObj = data.rslt.obj;
alert(selectedObj.attr("id"));
});
The json returned from your server must be in the correct format as defined in the jstree documentation, and must no include several special characters, unless those characters are escaped or the json created using serialization.

Categories

Resources