I have table that first time is server - side rendered. I want on some click event refresh data in table.
Problem is how to "bind" specific json object propertie to specific column. I receive json object with array of objects where only some of properties are interesting me.
I want
Table column -- json object propertie
ID -- id
Name -- name + surname
Cooperation -- scCooperationCollection
Skills -- scSkillsCollection
Experience -- workExperience
HTML table: http://pastebin.com/b5yRWsGe
JS reload table: http://pastebin.com/GzS8tpV6
JSON example : http://pastebin.com/AyBSrSui
See columns.data or columns.render options on how to bind source data to table columns or produce custom content for a cell.
You can access source data properties using dotted notation in columns.data or even join arrays with [] notation. For more complex data rendering like joining two fields, use columns.render instead.
For example:
var table = $('#example').DataTable({
ajax: {
url: 'https://api.myjson.com/bins/3x4ql',
dataSrc: 'aaData'
},
columns: [
{ data: "id" },
{
data: null,
render: function(data, type, full, meta){
return full['name'] + ' ' + full['surname'];
}
},
{ data: "scCooperationCollection[,].scFields.name" },
{ data: "scSkillsCollection[,].scFields.name" },
{ data: "workExperience" }
]
});
See this jsFiddle for code and demonstration.
You can navigate through the desired properties in returned json object and tie up same to your table something like below:
table.on( 'xhr', function () {
var json = table.ajax.json();
var obj = JSON.parse(json)
var tableJson = {"ID":obj.aaData[0].id};
console.log(json);
} );
Related
I wish to have an attribute called idField in my json object. Now this attribute is either an array if it contains multiple elements or just an object if it contains one element. I wish to create such an attribute from the data in an extjs store. In essence if the store contains just one element I need to insert this idField 'object' in the json object otherwise I need to insert an 'array' called idField in the json object. Please advise as to how to do that.
EDIT:
My store has 2 columns namely 'name' and 'type' in its data. What I wish is that if it contains just one element then my object should look like this:
{
...
idField : {
name : ...
type : ...
}
}
If my store contains 2 rows then my object should look like this :
{
...
idField : [
{
name : ...
type : ...
},
{
name : ...
type : ...
}
]
}
Also I have to INSERT this idField attribute inside the object. There is no currect idField attribute yet in the object.
EDIT 2:
I received this object in the console when I wrote console.log(Ext.getStore("My_store_name").data)
To get the data from the EXT JS store
var data = Ext.getStore("Your_Store_Name").data
In my snippet below I am assuming that you like to get the values from field name called item.
var data = Ext.getStore("Your_Store_Name").data
//imagine your JSON where you need to store is in variable myJSON
if (data.items.length == 1){
myJSON.idField = {type: 'sometype', name: data.item[0]} }
else if (data.item.length > 1)
{ //make an array of JSON
var list = [];
for(var i = 0; i < data.item.length; i++)
{
list.push({type: 'sometype', name: data.item[i]})
}
myJSON.idField = list; //set the array
}
In the past I've always used this to get a hidden column's data. I would hide the column with a css class, but the responsive feature doesn't work well with these.
var td = $('td', this);
var ID = $(td[0]).text();
So I found an alternative, by hiding the columns with these classes with the responsive feature.
"columnDefs": [
//Responsive classes
{ className: 'never', targets: 0 }, //Hide on all devices
{ className: 'all', targets: 1 }, //Show on all devices
]
and then I use either one of these.
var rowData = oTable1.fnGetData(this);
var rowData = oTable1.api().row(this).data();
//Grab the first indexed item in the list
var ID = rowData[0];
That works well if you don't have an AJAX source. It will return a comma separated list of the row data. However, when I try to use this with an AJAX source I just get [object Object] back (instead of a comma separated list) if I output the rowData variable in an alert.
How do I get the row data out of a table with an AJAX source?
It seem to be stored as string so [1, 2, 3] became [object Object] when you turn it into string. Do yourString = yourList.join(',') and store yourString to keep the coma-separated string.
For an object:
yourString = (function () {
var list = [];
for(var i in yourList)
if(yourList.hasOwnProperty(i))
list.push(yourList[i]);
return list.join(',');
})();
The function is not needed, it's just to limit the variables scope.
I ended up using an answer I found here.
Converting a JS object to an array
I can pull the entire row data from the table with this.
var rowData = oTable1.api().row(this).data();
In the console log I can see that it returns a javascript object like this.
Object { id="123456", full_name="Samuel Smith", Last_name="Smith" }
I use this function to convert the object into an array.
var array = $.map(rowData, function (value, index) {
return [value];
});
In the console log, my array would appear like this.
["123456", "Samuel Smith", "Smith"]
I can then extract any item from the array like this.
alert(array[0]);
Simplifying madvora's example:
var rowData = oTable1.api().row(this).data().to$();
rowDataArray = rowData.toArray();
I've made a simple ajax script (see code) which takes ID values from checkboxes that the user pressed, queries a database and construct a nested JSON-array for flot (containing one array for each ID chosen). Basically everything things work just perfect and all the arrays are being showed in the diagram. However, I'am looking for a solution to get the data, but instead of plotting them in the same diagram, I want to plot each JSON-array in the nested JSON-array in a separate diagram.
$.ajax({
type: "POST",
url: "includes/getjson.php",
data: $('.ids:checked').serialize(),
dataType: "json",
success: function(datasets){
var options = {
series: {
lines: { show: true },
points: { show: true }
},
xaxis: {
mode: "time",
timeformat: "%H:%M:%S",
twelveHourClock: true,
timezone: "browser"
},grid: {
hoverable: true,
clickable: true
}
}
$.plot($("#placeholder"), datasets, options);
}
});
I was thinking to dynamically creating the needed number of divs, maybe with a for-loop and then looping through the each array in the JSON. But I'm not sure how to do this? I could make my own parser and remove the outer-array so that I can simply split the array, but perhaps there is a better solution?
Another solution might be to make a .ajax call for each id-input from the checkboxes.
An example of an JSON where the ID are chosen can be seen here http://dinbab.dk/barline.json
Hei
I've just did something like that.
I needed a diagaram for each channel variable i had in db. What i did was putting the list of channelNames in ViewBag and used razor to create correct number of divs for the diagrams like that:
<div id="chartsDiv" class="column">
#{
int index = 0;
int heightDiv = 85 / (ViewBag.Channels.Count + 1);}
#foreach (var item in ViewBag.Channels)
{
<div id="#item.Replace(" ","")" title="#item" class="plot" style="height:#heightDiv%;"></div>
index++;
}
</div>
Then in script i do this:
var graphsArray = [];
var dataDetail;
$(function () {
var channelstxt = ('#ViewBag.ChannelsSerialized').replace(/"/g, '"')
var channels = JSON.parse(channelstxt);
var seriestxt = ('#ViewBag.SeriesJson').replace(/"/g, '"');
var seriesTab = jQuery.parseJSON(seriestxt);
$.each(channels, function (index, value) {
var elem = document.getElementById(value.toString().replace(/\s/g, ''));
var graph = $.plot(elem, [seriesTab[index]], getOptions(value));
graphsArray.push(graph)});
});
I get everything from ViewBag but you can easily get serialized json from ajax call.
I hope it helps! Ask it anything is unclear
I want to make specific json from table. I have a table, which has rows and 4 columns.
Here is my table I want to build an jsonarray from the table.
First value in the left column is key of json and last value in the right column is a valueof json.
I mean I want to get from table jsonarray, it must look as
json_from_form = [{color: 'id',
name: "mouse",
x: "table",
y: "book"}];
I have tried to build json, but have a problem with structure and setting a key in json object.
Please help me to buld right structure of json object.
var json_from_form_tmp = {};
$('#table').find('tbody tr').each(function (i) {
//var name = $(this).find('td:first').text();
json_from_form_tmp[i] = {
imd: $(this).find('td:eq(3) input').val()
};
});
console.log(json_from_form_tmp);
Here is my DEMO
You should use the jQuery map-function for this, here is an example:
$(function () {
var m = $("table tr").map(function (index, e) {
return {
color: $(e).children().eq(0).text(),
name: $(e).children().eq(1).text()
}
}).get();
});
Where m will be an array of objects as defined inside the map function.
To set a property of the object (json_from_form_tmp), use the ['propertyName'] notation.
//get the name of the property from the first column
var name = $(this).find('td:first').text();
//use that name as the name of the property. Your value fetch was right!
json_from_form_tmp[name] = $(this).find('td:eq(3) input').val();
Here is your fiddle with a tiny modification.
http://jsfiddle.net/bMzq8/32/
I have a JSON as follows
{
columns : [RULE_ID,COUNTRY_CODE],
RULE_ID : [1,2,3,7,9,101,102,103,104,105,106,4,5,100,30],
COUNTRY_CODE : [US,US,CA,US,FR,GB,GB,UM,AF,AF,AL,CA,US,US,US]
}
I need to retrive the column names from the columns entry and then use it to search the rest of the entries using jquery.
For example I get each column using
jQuery.each(data.columns, function(i,column))
I need to loop throgh the rest of the entries using the values I get from the previous loop. ie without hardcoding COUNTRY_CODE or RULE_ID.
What is the best way to do that using Jquery?
jQuery.each(data.columns, function(i,column) {
jQuery.each(data[column], function(i, row) {
....
});
});
Some comments:
Paolo is right, you can use data[column] to get the list of values:
jQuery.each(data.columns, function(iCol,column) {
jQuery.each(data[column], function(iRow, row) {
....
});
});
Do you need the columns information ? You could get the list of "columns" by iterating directly over data:
for( var column in data )
{
jQuery.each(data[column], function(i, row) {
....
});
}
Not really a question but your JSON is not valid JSON, I hope this was only an example and not your real data:
{
"columns" : ["RULE_ID","COUNTRY_CODE"],
"RULE_ID" : [1,2,3,7,9,101,102,103,104,105,106,4,5,100,30],
"COUNTRY_CODE" : ["US","US","CA","US","FR","GB","GB","UM","AF","AF","AL","CA","US","US","US"]
}