How to embed Json result within Extjs Panel? - json

I have some issues with Json result and embed it within the html of the Extjs Panel.
Here's that I have managed to get so far. myPanel is embedded within a mainPanel, and I have some shows/hide of the myPanel in between other sections of my codes.
Ajax request to retrieve Json result like so:
Ext.Ajax.request({
url: 'myStore',
success: function(r) {
var myItem = Ext.decode(r.responseText).itemName;
}
})
I would like to embed the myItem into mypanel, something like this:
var myPanel = new Ext.Panel({
hidden: true,
html:myItem
})
This is where the myPanel is embedded to my mainPanel:
var mainPanel = new Ext.Panel({
applyTo: 'mywizard',
frame: true,
items: [{
id: 'top',
xtype:'panel',
items: [
topPanel1,
topPanel2
]
},{
id: 'middle',
xtype: 'panel',
items: [
middlePanel1,
middlePanel2,
myPanel
]
},{
id: 'bottom',
xtype: 'panel',
items: [
footer
]
});
Currently if I were to run the code, I got a "undefined" within the myPanel, so I supposed that myItem is out of the scope, hence not picked up by myPanel. Hence, I would like to know how/what should I do to be able to get myItem (Json result) reflected in the myPanel?
Thank you.

I found the answer, tested and working for me. For any friends stuck with this. What I need to do is just to update the html content with the body update.
Basically, just grab the middle out of mainPanel such that:
var middle = new Ext.Panel({
id: 'middle',
xtype: 'panel',
items: [
middlePanel1,
middlePanel2,
myPanel
]
})
Of course, you will need to replace the middle back into the mainPanel.
Then, next is to create the myPanel as norm:
var myPanel = new Ext.Panel({
id: 'myPanel',
hidden: true,
html: 'empty'
})
Inside the Ajax request, you update
Ext.Ajax.request({
url: 'myStore',
success: function(r) {
var myItem = Ext.decode(r.responseText).itemName;
var editmycontent = Ext.getCmp('myPanel');
editmycontent.body.update(myItem); // update myItem here
middle.doLayout(); // refresh the changes
}
})
That's it!

you have a syntax error in this part the corrected code look like this :
var myPanel = new Ext.Panel({
hidden: true,
html:myItem // no ; here
});
also you have to be careful about scoping issue, if your code is in a class I would do something like that
Ext.Ajax.request({
url: 'myStore',
success: function(r) {
var myItem = Ext.decode(r.responseText).itemName;
var myPanel = new Ext.Panel({
hidden: true,
html:myItem // no ; here
});
this.parentPanel.add(myPanel);
}
,scope: this // note the set the scope
});

Related

EXTJS How to use JSon Reader without proxy

Below is the code where I try to load some records using JSon Reader in the store.
I am unable to see this on the Grid.
Can you please point me out what am I missing as I don't want to use proxy/url for JSon.
var itemsPerPage = 10;
Ext.Loader.setConfig({enabled: true});
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.util.*',
'Ext.toolbar.Paging'
]);
Ext.define('Assemble', {
extend: 'Ext.data.Model',
fields: [
{name: 'lot_no', type: "string"}
],
idProperty: 'lot_no'
});
Ext.onReady(function() {
Ext.QuickTips.init();
var jsonString = '{"result":[{"lot_no":"MT6261"},{"lot_no":"MT6262"},{"lot_no":"MT6263"}]}';
// create the data store
var store = Ext.create('Ext.data.Store', {
pageSize: itemsPerPage,
proxy:{
type: 'ajax',
reader: {
type: 'json',
root: 'result',
model: Assemble
}
}
});
store.loadData(Ext.decode(jsonString));
console.log(store);
var pagingToolbar = Ext.create('Ext.PagingToolbar',{
pageSize: itemsPerPage,
store: store,
displayInfo: true,
displayMsg: ' {0}-{1},{2}',
emptyMsg: "empty."
});
// create the Grid
var grid = Ext.create('Ext.grid.Panel', {
store: store,
disableSelection: true,
loadMask: true,
columns: [
{
text : 'LOT_NO',
flex : 1,
sortable : true,
dataIndex: 'lot_no'
}
],
bbar : pagingToolbar,
renderTo: 'grid',
viewConfig: {
stripeRows: true,
enableTextSelection: true
}
});
store.loadPage(1);
});
Proxy has to use with url. So, you can't use the proxy like that. I removed the proxy, put the model in store and you have to load objects into store, but in your case contained rootProperty('result', I only get the main objects or you can remove the 'result' from the jsonString). Then, it worked. Chck this fiddle:
https://fiddle.sencha.com/#fiddle/11or
var jsonString = '{"result":[{"lot_no":"MT6261"},{"lot_no":"MT6262"},{"lot_no":"MT6263"}]}';
// create the data store
var store = Ext.create('Ext.data.Store', {
pageSize: itemsPerPage,
model: 'Assemble'
});
store.loadData(Ext.decode(jsonString).result);
Why are you even using a reader? Your data is local so just decode the string and pass in what you want:
https://fiddle.sencha.com/#fiddle/11qc
Also, your data is local so no need for a paging toolbar. In Ext JS 5+ the grid will use the buffered renderer (if the grid has a defined size from height/width configs or from a parent layout) so loading all the data into the store will not affect performance (other than creating the records). The grid will only render what is viewable plus a few on either side.

Why is my JSON showing up in Kendo UI as Datasource.options.data but not Datasource.data?

New to Kendo and I'm having a tough time getting my JSON data to display in the Kendo Grid. If i reference my $scope.actionData through a normal html table, i'm able to view it in the page.
Ultimately I'm trying to accomplish this
The column headers display on the page, but no data beneath them.
When I'm attempting to populate the kendo grid, I can see the data I'm expecting through the Chrome Kendo UI Inspector in the DataSource -> Options -> Data Array, but I can't figure out how to get it to display on the page, and it's not populating the DataSource -> Data array. I've tried working through the examples on the angular-kendo page, but no luck. I've also tried adding various elements/tags under the div in the html, but I'm back where I started.
Let me know if I need to add anything else. Any assistance getting this to populate is greatly appreciated. Thanks in advance!
HTML:
<div kendo-grid k-data-source="gridOptions"></div>
Controller:
var actionHistoryControllers = angular.module('actionHistoryControllers', ['kendo.directives'])
.controller('ActionHistoryCtrl', ['$scope', '$routeParams', 'ActionHistory',
function ($scope, $routeParams, ActionHistory) {
$scope.actionData = ActionHistory.query({ appid: $routeParams.appid },
function (data) {
$scope.error = false;
$scope.errorMsg = "";
},
function (data) {
$scope.error = true;
$scope.errorMsg = "<strong>Unable to load!</strong> Please reload the page.";
});
$scope.gridOptions = {
data: $scope.actionData,
columns: [
{field: "UserID", title: "User ID"},
{field: "ActionText", title: "Action Text"}]
}
}])
Chrome Kendo UI Inspector:
Data source
options: Object{9}
data: Array[3]
0: Object{17}
ActionHistoryID: 315911
ActionText: "System"
...
Please replace the following:
$scope.gridOptions = {
data: $scope.actionData,
columns: [
{field: "UserID", title: "User ID"},
{field: "ActionText", title: "Action Text"}]
}
with the following:
$scope.gridOptions = {
dataSource: {
transport: {
read: function (o) {
o.success($scope.actionData);
}
},
columns: [
{field: "UserID", title: "User ID"},
{field: "ActionText", title: "Action Text"}]
}
}

Backbone toJSON not rending

I am a complete n00b to Backbone.js, and have only been working with it for a few days. I am attempting to fetch JSON data to populate the model, and in this scenario I have two models that I need to generate. Here is the sample JSON I have been working with:
JSON
{
"status": "200",
"total": "2",
"items":
[{
"id": "1",
"name": "Here is another name",
"label": "Label for test",
"description": "A description for more information.",
"dataAdded": "123456789",
"lastModified": "987654321"
},
{
"id": "2",
"name": "Name of item",
"label": "Test Label",
"description": "This is just a long description.",
"dataAdded": "147258369",
"lastModified": "963852741"
}]
}
Backbone JS
// MODEL
var Service = Backbone.Model.extend({
defaults: {
id: '',
name: '',
label: '',
description: '',
dateAdded: '',
dateModified: ''
}
});
var service = new Service();
// COLLECTION
var ServiceList = Backbone.Collection.extend({
model: Service,
url: "./api/service.php",
parse: function(response) {
return response.items;
}
});
//
var serviceList = new ServiceList();
var jqXHR = serviceList.fetch({
success: function() {
console.log("Working!");
console.log(serviceList.length);
},
error: function() {
console.log("Failed to fetch!");
}
});
// VIEW for each Model
var ServiceView = Backbone.View.extend({
el: $('.widget-content'),
tagName: 'div',
template: _.template($('#service-template').html()),
initialize: function() {
this.collection.bind("reset", this.render, this);
},
render: function() {
console.log(this.collection);
this.$el.html('');
var self = this;
this.collection.each(function(model) {
self.$el.append(self.template(model.toJSON()));
});
return this;
}
});
//
var serviceView = new ServiceView({
collection: serviceList
});
console.log(serviceView.render().el);
html
<div class="widget-content">
<!-- Template -->
<script type="text/template" id="service-template">
<div><%= name %></div>
</script>
</div>
When I console log the serviceList.length I get the value 2, so I believe the JSON object is fetched successfully. I also get the "Working!" response for success too. However, in the view I am showing an empty object, which gives me an empty model.
I am still trying to understand the best way to do this too. Maybe I should be using collections for the "items" and then mapping over the collection for each model data? What am I doing wrong? Any advice or help is greatly appreciated.
I can see two problems. First, you want to remove serviceList.reset(list). Your collection should be populated automatically by the call to fetch. (In any case the return value of fetch is not the data result from the server, it is the "jqXHR" object).
var serviceList = new ServiceList();
var jqXHR = serviceList.fetch({
success: function(collection, response) {
console.log("Working!");
// this is the asynchronous callback, where "serviceList" should have data
console.log(serviceList.length);
console.log("Collection populated: " + JSON.stringify(collection.toJSON()));
},
error: function() {
console.log("Failed to fetch!");
}
});
// here, "serviceList" will not be populated yet
Second, you probably want to pass the serviceList instance into the view as its "collection". As it is, you're passing an empty model instance into the view.
var serviceView = new ServiceView({
collection: serviceList
});
And for the view, render using the collection:
var ServiceView = Backbone.View.extend({
// ...
initialize: function() {
// render when the collection is reset
this.collection.bind("reset", this.render, this);
},
render: function() {
console.log("Collection rendering: " + JSON.stringify(this.collection.toJSON()));
// start by clearing the view
this.$el.html('');
// loop through the collection and render each model
var self = this;
this.collection.each(function(model) {
self.$el.append(self.template(model.toJSON()));
});
return this;
}
});
Here's a Fiddle demo.
The call serviceList.fetch is made asynchronously, so when you try console.log(serviceList.length); the server has not yet send it's response that's why you get the the value 1, try this :
var list = serviceList.fetch({
success: function() {
console.log(serviceList.length);
console.log("Working!");
},
error: function() {
console.log("Failed to fetch!");
}
});

How to get json with backbone.js

I am trying to use backbones.js fetch to get json from a twitter search
and my code below can someone tell me where I am going wrong?
(function($){
var Item = Backbone.Model.extend();
var List = Backbone.Collection.extend({
model: Item,
url:"http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&result_type=mixed"
});
var ListView = Backbone.View.extend({
el: $('#test'),
events: {
'click button#add': 'getPost'
},
initialize: function(){
_.bindAll(this, 'render', 'getPost');
this.collection = new List();
this.render();
},
render: function(){
var self = this;
$(this.el).append("<button id='add'>get</button>");
},
getPost: function(){
console.log(this.collection.fetch());
}
});
// **listView instance**: Instantiate main app view.
var listView = new ListView();
})(jQuery);​
I am just getting started with backbone and I just want to console.log the json
you can see my example here. jsfiddle.net/YnJ9q/2/
There are two issues above:
Firstly, you need to add a success/fail callback to the fetch method in order for you to have the fetched JSON logged to the console.
getPost: function(){
var that = this;
this.collection.fetch(
{
success: function () {
console.log(that.collection.toJSON());
},
error: function() {
console.log('Failed to fetch!');
}
});
}
Another problem is the issue of "same-origin-policy'. You can find out how to resolve that by taking a look at this link.
Update:
I modified your code and included the updated sync method. It now works! Take a look here!
Basically, update your collection to include the parse and sync methods as below:
var List = Backbone.Collection.extend({
model: Item,
url: "http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&result_type=mixed",
parse: function(response) {
return response.results;
},
sync: function(method, model, options) {
var that = this;
var params = _.extend({
type: 'GET',
dataType: 'jsonp',
url: that.url,
processData: false
}, options);
return $.ajax(params);
}
});

Sencha Touch not firing beforeshow event listener

Im new to sencha touch and going through the obligatory hair pulling and head2desk pounding.
Im trying to display a List but Im having a problem.
Im using a beforeshow event to load my json store before the list is displayed. But it's not firing the event. If any can help it is MOST appreciated.
My code is as follows: *note- this code is AS/400 centric so the /%...%/ is for that
function doList() {
var List1 = new Ext.List ({
id : List1,
renderTo : 'panel',
fullscreen: true,
showAnimation: {
type: 'slide',
duration: 250
},
cls: 'demo-list',
width: Ext.is.Phone ? undefined : 300,
height: 500,
store: ListStore,
itemTpl: '<strong>{SCEQPT}</strong>',
grouped: true,
indexBar: true,
onItemDisclosure: function(record, btn, index) {
doPopUp(record);
},
listeners: {
'beforeshow': function () {
alert('beforeshow');
var StoreList = Ext.StoreMgr.get('ListStore'
StoreList.load({
params: {
screfr: Ext.getCmp('SCREFR').getValue(),
scptyp: scptyp,
user : '/%SCUSER%/'
}
});
}
}
});
}
beforeshow listener is triggered only when you are displaying an item with show() method.
Try using the listeners
'render','beforerender' and 'afterrender'. instead.