Loading Flexigrid for jQuery with JSON String - javascript

I am trying to load the Flexigrid by using a JSON String which is returned by a WCF Service.
My Service has a public string GetContacts(string CustomerID) method and it returns a Json string.
That JSON string is created from a List object by using
System.Web.Script.Serialization.JavaScriptSerializer class. So, my aim is to bind the JSON string to the my Flexigrid as objects. I convert the web service result to objects using
var customer = eval("("+result+")");
The result is the JSON string being returned from service. Is there any way to bind customer objects to Flexigrid?

Flexigrid requires a format as follows in json
EDIT Thanks to EAMann for the format update.
total: (no of rec)
page : (page no)
rows : [{cell: [ (col1 value) , (col2 value) ,.. ] },
{cell: [ (col1 value) , (col2 value) ,.. ] }]
in order to bind the data to the grid i prefer sending the data across the wire and then formatting it on the client, but thats just me heres an example
function formatCustomerResults(Customers) {
var rows = Array();
for (i = 0; i < Customers.length; i++) {
var item = Customers[i];
//Do something here with the link
var link = "alert('opening item " + item.DealGuid + "');"
rows.push({
cell: [item.DealId,
item.Created,
item.CurrentStatus,
item.LastNote,
'<a href="javascript:void(0);" onclick="' + link + '" >view</a>'
]
});
}
return {
total: Customers.length,
page: 1,
rows: rows
};
}
and then all you need is
$("#FlexTable").flexAddData(formatCustomerResults(eval(data)));
ps this last bit is jquery syntax

almog.ori's answer is almost perfect. In fact, that's just about how I had built things before trying to Google the solution. One exception, though.
The JSON object should be:
total: (no of rec),
page : (page no),
rows : [{cell: [ (col1 value) , (col2 value) ,.. ] },
{cell: [ (col1 value) , (col2 value) ,.. ] }]
If you neglect the array format of the rows element, you'll end up choking Flexigrid and throwing all sorts of errors. But I've verified that this works flawlessly as long as you remember which parts of the script take JSON objects and which parts take arrays of JSON objects.

This is an older post but I thought I would add another way to use the excellent script provided by almog.ori.
The OP said that his data was being returned from a WCF service. If you mark the operation contract body style as bare you can use the preProcess property to add your formatCustomerResults (or other function) function to initially load the grid.
Like this:
$("#gridContainer").flexigrid({
url: '/YourService.svc/..',
method: 'GET',
dataType: 'json',
preProcess: formatCustomerResults,
...
});
function formatCustomerResults(data){
...
Hope this helps someone.

Make sure also that you are using the correct HTTP method, default is POST
To use GET:
$("#gridContainer").flexigrid({
url: '/json/files.json',
method: 'GET',
dataType: 'json',
...

preProcess solution by nameEqualsPNamePrubeGoldberg works perfect.
This is how my custom function for preProcess looks like.
var rows = Array();
$.each(data.rows,function(i,row){
rows.push({id:row.val1, cell:[row.val2,row.val3]});
});
return {
total:data.total,
page:data.page,
rows:rows
};

I recommend you to follow this sample to parse your JSON code and make requests to server:
Step 1: Parse using a function
function parsedForm(json)
{
var h = "";
if (json.post.val1)
h += "<b>Value 1</b>: " + json.post.val1 + "<br />";
h += "<b>Value 2</b>: " + json.post.val2 + "<br />";
h += "<b>Value 3</b>: " + json.post.val3 + "<br />";
if (json.post.val4)
h += "<b>Value 4</b>: " + json.post.val4 + "<br />";
$('#fdata').empty().html(h);
$('.formdata').slideDown();
return json;
}
Step 2: The flexigrid view code
$("#flex1").flexigrid({
url: 'post2.php',
dataType: 'json',
colModel : [
{display: 'ISO', name : 'iso', width : 40, sortable : true, align: 'center'},
{display: 'Name', name : 'name', width : 180, sortable : true, align: 'left'},
{display: 'Printable Name', name : 'printable_name', width : 120, sortable : true, align: 'left'},
{display: 'ISO3', name : 'iso3', width : 130, sortable : true, align: 'left', hide: true},
{display: 'Number Code', name : 'numcode', width : 80, sortable : true, align: 'right'}
],
searchitems : [
{display: 'ISO', name : 'iso'},
{display: 'Name', name : 'name', isdefault: true}
],
sortname: "iso",
sortorder: "asc",
usepager: true,
title: 'Countries',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 700,
onSubmit: addFormData,
preProcess: parsedForm,
height: 200
});
Step 3: Additonally, you can validate or serialize the data to request server
function addFormData(){
//passing a form object to serializeArray will get the valid data from all the objects, but, if the you pass a non-form object, you have to specify the input elements that the data will come from
var dt = $('#sform').serializeArray();
$("#flex1").flexOptions({params: dt});
return true;
}
$('#sform').submit(function (){
$('#flex1').flexOptions({newp: 1}).flexReload();
return false;
});
I hope it will help!

Make sure you have the dataType option set to json.
$('#gridContainer').flexigrid({
singleSelect: true,
showToggleBtn: false,
dataType: 'json'
});

I believe the latest flex code broke the solution using preProcess.
addData: function (data) { //parse data
if (p.dataType == 'json') {
data = $.extend({rows: [], page: 0, total: 0}, data);
}
if (p.preProcess) {
data = p.preProcess(data);
}
You need to flip it so that the preProcess if comes before the type JSON if. Otherwise the function listed as an answer does not work properly.

It's old, I know... But here is an example of json that works:
{
"total": 5,
"page": "1",
"rows": [
{"cell": [1, "asd", "dsa", "2013-07-30"]},
{"cell": [2, "asd", "dsa", "2013-07-30"]},
{"cell": [3, "asd", "dsa", "2013-07-30"]},
{"cell": [4, "asd", "dsa", "2013-07-30"]},
{"cell": [5, "asd", "dsa", "2013-07-30"]}
]
}
(5 results in total; first page (they are NOT zero-based); 5 lines of data, each containing { ID, "asd", "dsa", "a date" } )

Try to make total your first element in you JSON string like this.
`{"total" : 2,"page":1,"rows":[ {"cell" : ["226 CLAVEN LN", "312"]},{"cell" : ["1377 FAIRFAX PIKE","280"]}]}`

Related

Datatables: dropdown in a cell

i'm trying to generate a table with Datatables.
I receive a json from my controller, here a sample:
this json can change (number of columns, name of the columns) and I can build my table with the good number of column and the good name.
My question is:
How can i do to have a dropdown when the "liste" have an array and a simple input when it's null?
Is it even possible?
EDIT :
I forget to explain something. The Json that I receive is a json to build the table not to fill it. So is it possible to do a columnsDef before the datas are in the cell.
EDIT n°2:
I used the solution that I accepted, but the problem was with my json. I tried to send a json to build and a json to fill the table. So I change my json and I send the list of options in the json to fill the table.
Hope it will help other people.
Thanks
Here are two solutions:
1) With a drop-down.
2) With a formatted array (as an alternative).
1) With a Dropdown
The end result looks like this:
The datatables definition is this:
<script type="text/javascript">
var dataSet = { "records" : [
{ "data" : "123456789",
"liste" : null,
"name" : "Nombre Enfants"
},
{ "data" : "5678901234",
"liste" : [ "Oui", "Non" ],
"name" : "Transport"
}]};
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet.records,
columnDefs: [
{ targets: [ 0 ],
title: "Data",
data: "data" },
{ targets: [ 1 ],
title: "Liste",
data: function ( row ) {
if (row.liste == null) {
return null;
} else {
return buildDropdown(row.liste);
}
} },
{ targets: [ 2 ],
title: "Name",
data: "name" }
]
} );
function buildDropdown(data) {
var dropdown = "<select>";
for (var i = 0; i < data.length; i++) {
var option = "<option value=\"" + data[i] + "\">" + data[i] + "</option>";
dropdown = dropdown + option;
}
dropdown = dropdown + "</select>";
return dropdown;
}
} );
</script>
It builds a drop-down based on the assumption that a non-null value is an array. This may not always be the case in your data - just an assumption on my part.
2) With a formatted array
Just in case this is also of interest, DataTables has a built-in syntax for formatting array data, so it is displayed in a cell like this:
In this case, you no longer need the drop-down builder function. Everything else is the same as option (1) except for this part:
{ targets: [ 1 ],
title: "Liste",
data: "liste[, ]" },
Specifically, the [, ] notation lets you format the array data.
I mention this only because it lets you display all the array data in the cell, rather than neeeding to click a drop-down. But that is just a suggestion.
You may find that other functions such as searching and sorting are better with this option.
Update
The question has clarified that the table needs to be built dynamically from the data provided in the JSON.
You can pass variables to the datatables initializer - for example:
var col1 = { targets: [ 0 ], title: "Data", data: "data" };
var col2 = { targets: [ 1 ], title: "Liste", data: "liste" };
var col2 = { targets: [ 2 ], title: "Name", data: "name" };
var dynamicCols = [ col1, col2, col3 ];
The above col1 variable defines the title for the column, and where the column will get its data (from the dataSet.data fields).
The dynamicCols variable can then be used in a columnDefs as follows:
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet.records,
columnDefs: dynamicCols
} );
However, I am not aware of a way to include a function in a columndef, using this approach (for example to present a cell's data as a drop-down, if needed).
There are additional techniques which can be used to make a datatable even more dynamic - several examples are available online - for example here. Without seeing a more detailed example of the JSON being provided, I am not sure if there are any additional suggestions I can make.

how to access to json fields with webix and get data

I'm beginner with webix, Just started to link with mongodb.
Now, I started loading my data from my DB.
But when it comes to deal with Objects, I can't get the data.
webix.ready(function () {
var grida = webix.ui({
container: "testA",
id: "pivot", url: "/rent", save: "rest->/rent",
view: "pivot",
height: 400,
width: 1000,
max: true,
structure: {
rows: ["from"],
columns: ["created"],
}
});
});
and this is my json field that I copied from my mongoDB.
"from" : {
"agency" : ObjectId("554"),
"place" : ObjectId("554dc4"),
"date" : ISODate("2014-08-09T06:00:00.000+0000"),
"completed" : false
},
First, how to access to the data inside the object?
Thanks for your help :)
You can use "scheme" to preprocess data before loading it in the pivot
webix.ui({
id: "pivot",
scheme:{
$init:function(obj){
obj.phone = obj.phones? obj.phones[0].number : "Empty"
}
}

In kendo dataviz chart local data binding , JSON data value was spilted?

I create a Column chart using Kendo ui dataviz.
In my program, i am going to bind the local Javascript Array variable data to chart datasource.
The JSON data was spilted like "3""9""6" for "396".
I dont know why it happened. My Source code is given blow. Please check it and Please give the solution.
Source:
/**************Variable Declaration**********************************/
var eligibilityData = new Array();
eligibilityData = {
mem_status: {
a: 396, b: "56", c: "1125", d: "8423"
}
};
/**************Create Chart**********************************/
function createBarChart(eligibilityData) {
/****** Issue: A value is 396 but it spilted into "3","9","6"************/
$("#Chart1").kendoChart({
theme : $(document).data("kendoSkin") || "default",
dataSource : {
data: JSON.stringify(eligibilityData.mem_status.a),
},
seriesDefaults: { type: "column", },
series : [
{ field: "a", name : "A" }
],
tooltip : { visible: true, },
});
}
Local data should be passed as an array. No need to call JSON.stringify
data: [eligibilityData.mem_status]
See: http://docs.kendoui.com/api/framework/datasource#configuration-data-Array
JSON.stringify does not do what you expect. What you sentence really does is:
It gets the number 396 and converts it to a string.
Converts a string into an array of one character per element.
Not sure about the way you define the DataSource (why you want a DataSource with only one element) but if that is really what you want, you might try:
dataSource : {
data: [eligibilityData.mem_status.a]
},
or
dataSource : {
data: [eligibilityData.mem_status]
},

Json data not showing in extjs grid

Given data in the form:
var grid_data = [ {Hello: 'World'}, {Jesus:'Navas'} ]
I wish to draw a grid like so:
The grid shows with 2 rows but with no data, I can't find the problem in the following code:
var grid_store = Ext.create('Ext.data.Store', {
fields: [
{name: 'Property'},
{name: 'Value'}
],
data: grid_data
});
// create the Grid
var grid_view = Ext.create('Ext.grid.Panel', {
store: grid_store,
renderTo: 'info_panel',
stateful: true,
stateId: 'stateGrid',
columns: [
{
text : 'Property',
width : 100,
sortable : true,
dataIndex: 'Property'
},
{
text : 'Value',
width : 80,
sortable : false,
dataIndex: 'Value'
}
],
height: 350,
width: 600,
title: 'Array Grid',
viewConfig: {
stripeRows: true
}
});
Renders to:
<div id="info_panel"></div>
If you're wondering how I got the example image, I changed the store to an ArrayStore and re-formatted the data into arrays, but I'd prefer to miss out that step and insert the data as-is.
edit:
I think what I'm really asking for is a way to alert extjs to use the JSON keys as values, as opposed to most of the grid examples out there that take the form:
{value: 'Hello'}, {property: 'World'}
As one of the commenters and your edit suggested, your grid is built to consume a json with 'Property' and 'Value' being the keys for the json objects. I don't know if it's possible for you to change the source of the data to send in the reformatted json, but if not, you can always just run a quick loop to do so after receiving the data:
var new_data = [];
Ext.each(grid_data, function(obj) {
for (var prop in obj) {
new_data.push({
Property: prop,
Value: obj[prop]
});
}
}, this);

string passed does not render chart object, but string value if pasted into javascript directly does. Highcharts

On debug. when execution is leaving the controller I debug and the variable contains :
?sArray
{string[17, 2]}
[0, 0]: "Arecleoch"
[0, 1]: "21"
[1, 0]: "Barnesmore"
[1, 1]: "3"
etc etc....
then in the javascript its received as :
?sdata
{...}
[0]: "Arecleoch"
[1]: "21"
[2]: "Barnesmore"
[3]: "3"
[4]: "Beinn An Tuirc"
[5]: "1"
[6]: "Beinn An Tuirc Phase 2"
etc
so the pie is displayed as one solid circle of colour
puzzled, any ideas?
controller code below :
public JsonResult GetChartData_IncidentsBySite()
{
var allSites = _securityRepository.FindAllSites();
var qry = from s in _db.Sites
join i in _db.Incidents on s.SiteId equals i.SiteId
group s by s.SiteDescription
into grp
select new
{
Site = grp.Key,
Count = grp.Count()
};
string[,] sArray = new string[qry.Count(),2];
int y = 0;
foreach (var row in qry.OrderBy(x => x.Site))
{
if ((row.Count > 0) && (row.Site != null))
{
sArray[y, 0] = row.Site.ToString();
sArray[y, 1] = row.Count.ToString();
y++;
}
}
return Json(sArray , JsonRequestBehavior.AllowGet);
}
Here is the javascript code :
$.getJSON(url, null, function(sdata) {
debugger;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Number of Environmental Incidents by Site'
},
tooltip: {
formatter: function() {
return '<b>' + this.point.name + '</b>: ' + this.y + ' %';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Incidents by Site',
data: sdata
}]
});
});
});
In the version that works, data is an Array of Arrays of String ;
data: [["Arecleoch",21], ...
(Notice there is no oppening quotes before the first bracket).
In the version that does not work, it is a String representing the Array.
I suspect the charts API only expect an Array (in this case, an array of array, actually).
So it depends on what this does :
$.getJSON(url, null, function(data) {
// What is the type of data here ?
From your controller and the display of your debugger, I think data is itself an Array of Arrays. You should directly pass it to the charts API (without the sData = data.toString()) function wich actually transforms the Array ['a', 'b', 'c'] into a String representing the array, like "['a', 'b', 'c']");
// Callback parameter renamed to show it is an Array of Arrays
$.getJSON(url, null, function(aaData) {
// ... skipped ...
series: [{
type: 'pie',
name: 'Incidents by Site',
data: aaData /* Use the Array itself */
}]
Edit : my solution will only work if the controller output something like :
{
data : [[ "Arecleoch", 21], ["Whatever", 42]]
}
However it seems like your controller returns something like
{
data : "[['Arecleoch', 21],['Whatever', 42]]"
}
(Maybe without the { data : } part, I don't know if you need a top-level element or if you are derectly returning the Array in JSON)
Is that the case ? If so, then you'll have to either :
change the controller
parse the string on the client side, in javascript

Categories