I have JSON response as below -
{
"success": true,
"data": {
"data": [
{
"resultsMap": {
"Title": "Test1",
"Name": "Test1"
},
"id": 1
},
{
"resultsMap": {
"Title": "Test2",
"Name": "Test2"
},
"id": 2
}
],
"total": 2
}
}
I am using a custom reader to extract the data. Problem is I loose the initial JSON response from the server from which I need to extract the "total". Can someone help me in getting the "total" from the json response?
var newStore = Ext.create('Ext.data.BufferedStore', {
pageSize: 2000,
fields:fields,
//leadingBufferZone:50,
//trailingBufferZone:50,
//autoLoad: {start: 0, limit: 2000},
remoteSort: true,
sorters: [{
property : 'name',
direction: 'asc'
}],
proxy: {
type: 'ajax',
url: 'getData.json',
reader: {
type: 'nestedjsonreader',
rootProperty: 'data',
totalProperty: function(data) {
//console.log(data);
return data.totalCount;
},
},
extraParams: {
id:ID
}
},
listeners: {
'load' : function(store, records, success, options){
//the complete response
console.log(store.getProxy().getReader().rawData);
}
}
});
Ext.define('Portal.model.NestedJsonReader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.nestedjsonreader',
readRecords: function(data) {
var arr = data.data.data;
var data = [];
if(arr!=undefined){
for(var i=0;i<arr.length;i++){
var obj = arr[i].resultsMap;
data.push(obj);
}
}
return this.callParent( [ data ]);
}
})
Create a custom property in your store as resp_total and assign data.total to it.
Related
Hi I'm currently having trouble with datatable. My datasource is object and I want every first key in the object displayed as value in datatable. Here is my code.
var my_data = {
"content": [
{
"data_v1": [{"id" : 1}]
},
{
"data_v2": [{"id" : 2}]
},
{
"data_v3": [{"id" : 3}]
}
]
};
$(document).ready(function() {
$('#example').DataTable( {
data:my_data,
columns: [
{ data: 'content'
}
]
} );
} );
What output I expect is this.
| Content |
-------------
data_v1
data_v2
data_v3
Note: As long as posible, I don't want to use forloop or any kind of loop. TIA
Any help will be so much appreciated.
Try
var myData = {
"content": [
{
"data_v1": [{"id" : 1}]
},
{
"data_v2": [{"id" : 2}]
},
{
"data_v3": [{"id" : 3}]
}
]
};
$(document).ready(function()
{
$('#example').DataTable( {
data: Object.keys(myData["content"]),
columns: [
{ title: 'content'
}
]
});
});
Object.keys will return an array of keys from the data provided
This answer is from #colin of Datatable.
$(document).ready(function() {
var my_data = {
"contents": [{
"data_v1": [{
"id": 1
}]
},
{
"data_v2": [{
"id": 2
}]
},
{
"data_v3": [{
"id": 3
}]
}
]
};
var table = $('#example').DataTable({
data: my_data.contents,
columnDefs: [{
targets: 0,
render: function(data, type, row, meta) {
return (Object.keys(row)[0]);
}
}]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet"/>
<table id="example"></table>
I want to implement function in which data will be loaded into datatable after onChange event. So for that I am trying to implement code as below.
var viewdatatab = $('#dataTablesFeedback').dataTable({
"columns": [
{ "data": "resourceId" },
{ "data": "feedbackRecommendation" },
{ "data": "technicalSkillGaps" },
{ "data": "technicalAvgSkills" },
{ "data": "feedbackType" },
{ "data": "feedbackId" },
{ "data": "isNew" },
]
});
Which is creating my datatable layout and I am calling below function on dropdown change event is :
function loadFeedback(){
viewdatatabJS = $('#dataTablesFeedback').dataTable({
"processing" : true,
"retrieve" : true,
"ajax" : "/nhp/rest/feedback/viewFeedback",
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "userName", "value":employeeId } ,
{ "name": "resourceId", "value":mentorDataJson[$('#dropDownId').val()].resourceId });
},
});
}
Where I am passing some parameter in aoData.push but my URL is not getting called.
I Solved the issue by simply implementing datatable properties. i wrote my code of datatable
var viewdatatab = $('#dataTablesFeedback').dataTable({
"columns": [
{ "data": "resourceId" },
{ "data": "feedbackRecommendation" },
{ "data": "technicalSkillGaps" },
{ "data": "technicalAvgSkills" },
{ "data": "feedbackType" },
{ "data": "feedbackId" },
{ "data": "isNew" },
]
});
in jsp document.ready(function()) and then on my request call of drop down change event i wrote below code on my javascript function.
$.ajax({
url : "",
type: 'GET',
contentType: "application/json",
data: {
'userName': value,
'resourceId' : value,
},
success: function(data) {
var table = $('#dataTablesFeedback').DataTable();
table.clear();
table.rows.add(data.data);
table.draw();
});
this way i first clear my datatable and then redraw it using my json which i got from my ajax call.
Thanks
I am developing an application where I need to fetch the menu items from a text file.
I am new to JQX.
But while displaying the records its showing nothing.
My Text File(LeftMenu.txt) as below:
[{
"text": "Menu1",
"id": "1",
"parentid": "-1"
},
{
"text": "Menu2",
"id": "2",
"parentid": "-1"
},
{
"text": "Menu3",
"id": "3",
"parentid": "-1"
}
]
==========================================================================
The code is here under
// prepare the data for Left Menu
var urlleftpanel = "../../Public/sampledata/leftmenu.txt";
var sourceleftmenu =
{
datatype: "json",
datafields: [
{ name: 'id' },
{ name: 'parentid' },
{ name: 'text' }
],
id: 'id',
url: urlleftpanel
};
// create data adapter.
var dataAdapter1 = new $.jqx.dataAdapter(sourceleftmenu);
// perform Data Binding.
dataAdapter1.dataBind();
var records = dataAdapter1.getRecordsHierarchy('id', 'parentid', 'items', [{ name: 'text', map: 'label' }]);
var records = da.records;
$('#jqxWidget').jqxMenu({ source: records , height: 53, theme: theme, width: '95px' });
=====================================================================================
Please Help its very urgent
Thanks in Advance
Try setting async: false in the source object.
var sourceleftmenu =
{
datatype: "json",
async: false,
datafields: [
{ name: 'id' },
{ name: 'parentid' },
{ name: 'text' }
],
id: 'id',
url: urlleftpanel
};
I asked this question earlier this morning
"here is my JSON file :
[
{
"Week": "1145",
"Sev_Logged": "3_major",
"From": "IN1"
},
{
"Week": "1145",
"Sev_Logged": "4_minor",
"From": "IN1"
},
{
"Week": "1145",
"Sev_Logged": "4_minor",
"From": "IN1"
},
{
"Week": "1145",
"Sev_Logged": "4_minor",
"From": "IN1"
},
{
"Week": "1145",
"Sev_Logged": "4_minor",
"From": "IN1"
},
{
"Week": "1145",
"Sev_Logged": "4_minor",
"From": "IN2"
},
{
"Week": "1145",
"Sev_Logged": "3_major",
"From": "IN2"
},
];
I want to count the "from : IN1" field for each "week", per example for week : 1145 i'd get : 3, and for "From : IN2" i'd get 2
Thanks"
Thank you VDP for your answer, so I did this :
My store is now like :
Ext.define('Metrics.store.GraphData', {
extend : 'Ext.data.Store',
model : 'Metrics.model.GraphData',
autoload : true,
proxy : {
type : 'ajax',
url : 'data/metrics_data.json',
reader : {
type : 'json',
root : 'data',
successProperty : 'success'
}
},
//data : GraphData, //povide inline data or load using proxy
countBy: function(param){
var count = {};
this.each(function(item){
var type = item.get(param);
if (Ext.isDefined(count[type])){
count[type]++;
} else {
count[type] = 1;
}
});
return count;
}
});
And my model :
Ext.define('Metrics.model.GraphData', {
extend: 'Ext.data.Model',
//fields: ['week', 'sev']
fields : [
{name: 'Week', type: 'int'},
{name: 'Sev_Logged', type: 'string'},
{name: 'From', type: 'string'}
]
});
Since i'm using extjs 4 with MVC model, I have made a controller wich controls the event of a button, right now it looks like this :
launchGraph : function(button){
console.log('clicked the apply button');
var chartStore = this.getGraphDataStore();
chartStore.load({
callback: this.onGraphDataLoad,
scope: this,
console.log(chartStore.countBy("From"))
});
But when I click the apply button I get this error in my controller :
"Uncaught SyntaxError: Unexpected token . "
And it points to the line :
"console.log(chartStore.countBy("From"))"
It seems like i have an error in the referencing to my store. Any ideas?
If var jsonData is the array resulting from parsing the json shown above, this will give you an object with the counts of each depending on the parameter you use..
function CountBy(parameter) {
var count = {};
for (var i = 0; i < jsonData.length; i++) {
var type = jsonData[i][parameter];
if (count[type] === undefined) {
count[type] = 1;
} else {
count[type]++;
}
}
return count;
}
Result:
CountBy("From") => {"IN1" : 5, "IN2" : 2}
CountBy("Week") => {"1145" : 7}
CountBy("Sev_Logged") => {"3_major": 2, "4_minor": 5}
If you are using the array you provide you can just use the mimikomi's answer or a similar ExtJS version of it:
here is a fiddle
function countBy(data, param) {
var count = {};
Ext.each(data, function(item){
var type = item[param];
if (Ext.isDefined(count[type])) {
count[type]++;
} else {
count[type] = 1;
}
});
return count;
}
If you load that json from an external location it's best practice to load it in a store. You define a model, a store and add 'special' functions to your store for example.
Ext.define('Week', {
extend: 'Ext.data.Model',
fields: [
{name: 'Week', type: 'int'},
{name: 'Sev_Logged', type: 'string'},
{name: 'From', type: 'string'}
]
});
var store = Ext.create('Ext.data.Store', {
model: 'Week',
data : data, //povide inline data or load using proxy
countBy: function(param){
var count = {};
this.each(function(item){
var type = item.get(param);
if (Ext.isDefined(count[type])){
count[type]++;
} else {
count[type] = 1;
}
});
return count;
}
});
var countObject = store.countBy("From");
alert(Ext.encode(countObject));
//chrome developper tools, safari, opera can show us the contents of objects in a log too. IE, FF however only tell us it is an object. (pretty useless)
console.log(countObject);
//you can chose you're favorite notation to retreve the value (but I hope you knew this, it's pretty basic javascript)
console.log(countObject.IN1);
console.log(countObject['IN2']);
Here is a fiddle.
More info on loading json dynamically into a store via ajax (using a proxy)
I had a sencha touch code which connects to a WebService using Ext.Ajax.request. On success function, I want the response to be displayed in a list or store it in a Store.
Please help me how to do that. Below is my code.
var View = function() {
Ext.getBody().mask('Loading...', 'x-mask-loading', false);
Ext.Ajax.request({
url: 'URL',
method: 'GET',
success: function(response, opts)
{
var obj = Ext.util.JSON.decode(response.responseText);
Ext.getCmp('content').update(response.responseText);
}
});
};
create a Ext.List with store attribute,
myStore = new Ext.data.Store({
model: Ext.regModel('', {
fields: [
{ name: 'id', type: 'int' },
{ name: 'name', type: 'string'},
{ name: 'age', type: 'string'}
]
})
});
myList = new Ext.List({
store: myStore,
itemTpl: '<div>{name}</div>' +'<div>{age}</div>'
});
Then fill the myStore store with results of Agax request. onsuccess event in ajax call should be as follows,
var jsonData = Ext.util.JSON.decode(response.responseText);
myStore.add(jsonData['myresultlist']);
myStore.sync();
Then make sure You are returning a valid json from the server side as follows,
{
"myresultlist": [
{
"id": "1",
"name": "anne",
"age": "21"
},
{
"id": "2",
"name": "jack",
"age": "26"
},
{
"id": "3",
"name": "Tom",
"age": "21"
}
],
"success": "true",
"info": "My Results List!"
}