ExtJS AJAX returned JSON object - json

I have an AJAX call inside an ExtJS script, but I'm not sure how to take the returned JSON object and assign it to a variable for use on the page. I'm basically taking a hardcoded extJS script and puting in JSON from database. Here is what I need to do
Get a variable from this AJAX call:
Ext.onReady(function () {
Ext.Ajax.request({
url: '/xxx/clienttool/components/Client-Tool.cfc?method=getResources&returnformat=json',
params: {
accountID: 463
},
success: function(response){
var text = response.responseText;
// process server response here
}
});
and assign it so these values aren't hardcoded:
// Store holding all the resources
resourceStore : Ext.create("Sch.data.ResourceStore", {
model : 'Sch.model.Resource',
data : [
{Id : 'MadMike', Name : 'Mike'},
{Id : 'JakeTheSnake', Name : 'Jake'},
{Id : 'KingFu', Name : 'King'},
{Id : 'BeerBrian', Name : 'Brian'},
{Id : 'LindaAnderson', Name : 'Linda'},
{Id : 'DonJohnson', Name : 'Don'},
{Id : 'KarenJohnson', Name : 'Karen'},
{Id : 'DougHendricks', Name : 'Doug'},
{Id : 'PeterPan', Name : 'Peter'}
]
}),
Here's the whole thing:
Ext.onReady(function () {
App.SchedulerDemo.init();
});
App.SchedulerDemo = {
// Initialize application
init : function () {
Ext.define('Event', {
extend : 'Sch.model.Event',
fields : [
{name : 'Title'},
{name : 'Type'}
]
});
//ajax call to get resources for this accountID
Ext.Ajax.request({
url: '/xxxx/clienttool/components/Client-Tool.cfc?method=getResources&returnformat=json',
params: {
accountID: 463
},
success: function(response){
getResources = response.responseText;
// process server response here
}
});
//alert(getResources);
var zoneStore = Ext.create('Ext.data.JsonStore', {
model : 'Sch.model.Range',
data : [
{
// Nice 2 hour lunch
StartDate : new Date(2011, 11, 9, 12),
EndDate : new Date(2011, 11, 9, 14),
Cls : 'lunch-style'
}
]
});
var sched = Ext.create("Sch.panel.SchedulerGrid", {
height : ExampleDefaults.height,
width : ExampleDefaults.width,
rowHeight : 40,
eventBarTextField : 'Title',
viewPreset : 'hourAndDay',
startDate : new Date(2011, 11, 9, 7),
endDate : new Date(2011, 11, 9, 20),
orientation : 'vertical',
constrainDragToResource : false,
eventBarIconClsField : 'Type',
snapToIncrement : true,
//constrainDragToResource : true,
eventResizeHandles : 'end',
viewConfig : {
// Experimental for CSS3 enabled browsers only
eventAnimations : true
},
// Store holding all the resources
resourceStore : Ext.create("Sch.data.ResourceStore", {
model : 'Sch.model.Resource',
data :
[
{Id : 'MadMike', Name : 'Mike'},
{Id : 'JakeTheSnake', Name : 'Jake'},
{Id : 'KingFu', Name : 'King'},
{Id : 'BeerBrian', Name : 'Brian'},
{Id : 'LindaAnderson', Name : 'Linda'},
{Id : 'DonJohnson', Name : 'Don'},
{Id : 'KarenJohnson', Name : 'Karen'},
{Id : 'DougHendricks', Name : 'Doug'},
{Id : 'PeterPan', Name : 'Peter'}
]
}),

If the only purpose of the AJAX request is to retrieve data for your grid's store, I would ditch it altogether and simply define an AJAX proxy on your store. It will not only accomplish the same initial objective (e.g., getting data for your store), but will also handle creating model instances of your data and binding the store to your grid.
I would suggest checking out the docs for the Store, as well as the grid examples in the documentation.

Related

How to add trajectory orientation to CZML file

I have a czml file representing an aircraft flying a specified path. The file is constructed based on the Sancastle examples provided by Cesiusm (CZML Model + CZML Path).
Here is the CZML variable:
var czml = [{
"id" : "document",
"name" : "CZML Path",
"version" : "1.0",
"clock": {
"interval": "2012-08-04T10:00:00Z/2012-08-04T15:00:00Z",
"currentTime": "2012-08-04T10:00:00Z",
"multiplier": 10
}
}, {
"id" : "path",
"name" : "path with GPS flight data",
"description" : "<p>Hang gliding flight log data from Daniel H. Friedman.<br>Icon created by Larisa Skosyrska from the Noun Project</p>",
"availability" : "2012-08-04T10:00:00Z/2012-08-04T15:00:00Z",
"path" : {
"material" : {
"polylineOutline" : {
"color" : {
"rgba" : [255, 0, 255, 255]
},
"outlineColor" : {
"rgba" : [0, 255, 255, 255]
},
"outlineWidth" : 5
}
},
"width" : 8,
"leadTime" : 10,
"trailTime" : 1000,
"resolution" : 5
},
"model": {
"gltf" : "../../SampleData/models/CesiumAir/Cesium_Air.glb",
"scale" : 2.0,
"minimumPixelSize": 128
},
"position" : {
"epoch" : "2012-08-04T10:00:00Z",
"cartographicDegrees" : [
0,-122.93797,39.50935,1776,
10,-122.93822,39.50918,1773,
20,-122.9385,39.50883,1772,
30,-122.93855,39.50842,1770,
40,-122.93868,39.50792,1770,
50,-122.93877,39.50743,1767,
60,-122.93862,39.50697,1771,
70,-122.93828,39.50648,1765,
80,-122.93818,39.50608,1770,
90,-122.93783,39.5057,1754,
100,-122.93777,39.50513,1732,
110,-122.93793,39.50458,1727,
120,-122.93815,39.50415,1717,
130,-122.9382,39.50362,1713,
140,-122.93818,39.5031,1703,
150,-122.93812,39.50258,1706,
160,-122.93792,39.5022,1707,
170,-122.93775,39.50177,1698,
180,-122.93745,39.50125,1693,
190,-122.93723,39.50073,1694,
200,-122.9373,39.50023,1702
]
}
}];
In order to be able to run the the code I also add the following lines:
var terrainProvider = new Cesium.CesiumTerrainProvider({
url : 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
requestVertexNormals : true
});
var viewer = new Cesium.Viewer('cesiumContainer', {
terrainProvider : terrainProvider,
baseLayerPicker : false
});
viewer.dataSources.add(Cesium.CzmlDataSource.load(czml)).then(function(ds) {
viewer.trackedEntity = ds.entities.getById('path');
});
If you run the code you can see how the center point of the aircraft follows the trajectory, however its heading is not aligned with it thus giving a wrong rap presentation of what the flight should look like:
Would you be able to explain how to add the aircraft orientation to the the code without possible changing the initial czml file structure?
Note: I have found the answer to this question but I was not able to implemented to my problem.
I came up with an answer to the my question. Here there are the lines of codes that if placed in Sandcastle will allow to load the czml file and then add the orientation property through some type of interpolation:
//Sandcastle_Begin
var terrainProvider = new Cesium.CesiumTerrainProvider({
url : 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
requestVertexNormals : true
});
var viewer = new Cesium.Viewer('cesiumContainer', {
terrainProvider : terrainProvider,
baseLayerPicker : false
});
var options = {
camera : viewer.scene.camera,
canvas : viewer.scene.canvas
};
Sandcastle.addToolbarMenu([{
text : 'Lateral avoidance w. real Wx and waypoints (KJFK-LEBL)',
onselect : function() {
viewer.camera.flyHome(0);
viewer.dataSources.add(Cesium.CzmlDataSource.load('./SampleData/interp_turb_data_fromFede_avoid_realistic_w_waypoints.czml')).then(function(ds) {
var entity = ds.entities.getById('path');
// viewer.trackedEntity = entity;
entity.orientation = new Cesium.VelocityOrientationProperty(entity.position);
entity.position.setInterpolationOptions({
interpolationDegree : 1,
interpolationAlgorithm : Cesium.HermitePolynomialApproximation
});
});
}
}], 'toolbar');
Sandcastle.reset = function() {
viewer.dataSources.removeAll();
viewer.clock.clockRange = Cesium.ClockRange.UNBOUNDED;
viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK;
};
//Sandcastle_End
In this way the aircraft will be aligned with the trajectory!

Can not print child properties of mongodb document with nodejs

I have a list of user's documents in mongodb which is carrying fields like this:
{
"_id" : ObjectId("57fb60caf380e20df0d59f4d"),
"signupFp" : "a47d436a33edb44dfd2c45d6eb5574bd",
"signupIp" : "127.0.0.1",
"password" : "d38c2a8589965d869c79ce77e4dc871e",
"email" : "someemail#gmail.com",
"createTime" : ISODate("2016-10-10T09:35:06.386Z"),
"isAdmin" : false,
"isActive" : true,
"account" : [
{
"port" : 5001,
"server" : "harish server"
},
{
"port" : 7001,
"server" : "harish server"
}
],
"__v" : 0,
"sendEmailTime" : ISODate("2016-10-10T09:35:06.405Z"),
"activeKey" : "61ce67b47ee15547878404d9b5bebab7",
"lastLogin" : ISODate("2016-10-12T07:51:53.059Z"),
"expireTime" : ISODate("2016-10-25T00:00:00.000Z")
}
I am fetching all the user's document using nodejs with the following code:
var User = mongoose.model('User');
User.find({}).exec(function(err, data){
if(err){
return;
}
data.forEach(function(user){
if(user.expireTime < new Date()){
console.log(user.lastLogin); //prints the last login date
console.log(user.account); //outputs []
console.log(user.account.port); //outputs undefined
}
}
}
and further i need value of child nodes i.e account.port and account.server but when i console.log its giving me blank array [] or undefined to console.log a specific child key
How do i get the account.port and account.server values
You have specified var User = mongoose.model('User'); you don't need to do it in the logs anymore (user.lastLogin),(user.account),(user.account.port) just omit the user from all of them, should work.
(lastLogin)
(account)
(account.port)

How do you insert an array of object into Mongodb node.js

Basically i want to insert into my Mongodb collection called "Events" an array of objects called "Events" with an id for each entry into the array.
This is the result i want to get in json:
{
"events" : [
{
"_id" : ObjectId("53a99cc608ad49712a830081"),
"eTitle" : "Freshers Fair",
"eDesc" : "Bring some friends with you oh wait, you have non ha !",
"eDate" : "2014-06-19 11:20",
"eLink" : "http://fair.com",
"eEvent" : "NEFS"
},
{
"_id" : ObjectId("53a99cc608ad49712a830082"),
"eTitle" : "Blahh",
"eDesc" : "Blah fdinidf !",
"eDate" : "2014-06-19 11:20",
"eLink" : "http://google.com",
"eEvent" : "NEFS"
}
]
}
So far this is the result i have:
[
{
"_id":"53a9b5ed745363432d823d7a",
"eTitle":"jrnfdeiujn rd",
"eDesc":"grfdsreds",
"eDate":"2014-07-05 22:33",
"eLink":"reser",
"eEvent":"Victoria Center"
},
{
"_id":"53a9b771745363432d823d7b",
"eTitle":"Hello worlds",
"eDesc":"blah",
"eDate":"2014-07-20 22:33",
"eLink":"http://google.com",
"eEvent":"social"
}
]
This is how i insert data with node.js:
// Set our collection
var collection = db.get('Events');
// Submit to the DB
collection.insert({
"eTitle" : eTitle,
"eDesc" : eDesc,
"eDate" : eDate,
"eLink" : eLink,
"eEvent" : eEvent
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
// If it worked, set the header so the address bar doesn't still say /adduser
res.location("eventlist");
// And forward to success page
res.redirect("eventlist");
}
});
So please i how do i make the format look this the first json format i provided. sorry for the nooby question, just started learning node ! Thanks alot
UPDATE
To post Events:
router.get('/eventlist', function(req, res) {
var db = req.db;
var collection = db.get('Events');
collection.find({},{},function(e,docs){
console.log(docs);
res.send(docs);
// res.render('eventlist', {docs: JSON.stringify(docs), title: 'Test'});
});
});
You can do this:
collection.find({},{},function(e,docs){
var doc = { Events : docs };
console.log(doc);
res.send(doc);
// res.render('eventlist', {docs: JSON.stringify(docs), title: 'Test'});
});

RKEntityMapping JSON array RKResponseDescriptor keypath issue possibly

I am attempting to map my Core Data "Component" Entity to the "hotspots" keypath in this response JSON, but it only gets to the array object so it will not map. I can't tell if my problem is the mapping or the response descriptor or a combination of the two.
"result" : {
"type" : "Slidedeck",
"id" : 81,
"name" : "Brendantest",
"slides" : [
{
"thumb" : "http:\/\/api.idetailapp.review.thingee.com\/v4\/resources\/1294\/download\/slide?thumb=true",
"id" : 1294,
"notes" : "",
"label" : "",
"order" : 1,
"parent_id" : 81,
"file" : "slide-20.jpg",
"components" : {
"hotspots" : [
{
"x" : 205,
"options" : "embedded",
"type" : "video",
"id" : 6082,
"y" : 453,
"assets" : [
{
"thumb" : "\/system\/asset_objects\/14\/original_thumb\/14.png",
"id" : 14,
"parent_id" : 6082,
"file" : "slide_15_chart_animation_ipad_r03.mov",
"url" : "http:\/\/api.idetailapp.review.thingee.com\/v4\/resources\/14\/download\/asset"
}
],
"parent_id" : 1294,
"width" : 320,
"height" : 246
}
]
},
"url" : "http:\/\/api.idetailapp.review.thingee.com\/v4\/resources\/1294\/download\/slide"
}
],
"version" : "0.43"
}
}
Here is my RKEntityMapping:
RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:#"Component"
inManagedObjectStore:[RKManagedObjectStore defaultStore]];
mapping.identificationAttributes = #[ #"componentID" ];
[mapping addAttributeMappingsFromDictionary:#{#"id": #"componentID",
#"parent_id": #"parentID"
}];
[mapping addAttributeMappingsFromArray:#[#"x", #"y", #"width", #"height", #"type", #"options"]];
Here is my Responsedescriptor:
componentResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:componentEntityMapping
method:RKRequestMethodAny pathPattern:nil
keyPath:#"result.slides.components.hotspots" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
I put in a RestKit/ObjectMapping debug trace and get to the following output:
Asked to map source object (
{
assets = (
{
file = "slide_15_chart_animation_ipad_r03.mov";
id = 14;
"parent_id" = 6082;
thumb = "/system/asset_objects/14/original_thumb/14.png";
url = "http://api.idetailapp.review.thingee.com/v4/resources/14/download/asset";
}
);
height = 246;
id = 6082;
options = embedded;
"parent_id" = 1294;
type = video;
width = 320;
x = 205;
y = 453;
}
And further debug message of:
Failed transformation of value at keyPath 'id' to representation of type 'NSNumber': Error Domain=org.restkit.RKValueTransformers.ErrorDomain Code=3002 "Failed transformation of value '(
6082
)UserInfo=0x12479350 {NSLocalizedDescription=Expected an inputValue of type NSNull, but got a __NSArrayI.}"
),
Your problem is keyPath:#"result.slides.components.hotspots".
Specifically, the fact that slides is an array.
The result is that RestKit is asked to map an array of objects into your mapping. So, when it tries to get the id (which should be a number), it gets an array (hence your error). This is because calling valueForKey: on an array returns an array...
So, basically, you can't do it the way you're trying to because of the array in the middle of the JSON.
If you can get the JSON changed, do that. If you can't, you need to change your mapping to map the slides first and then the nested components (then you can discard the slides afterwards if you want).

EXT Js Complex JSON Response Handling : Grid Insertion

Hello I am trying to insert a JSON record into the grid dynamically.
My server response is as below :
{
"studentDetails":{
"status":"ACTIVE",
"subject":"MATH",
"paymentOptions":"EFT",
"idStudent":71,
"firstName":"Alli",
"lastName":"Alli",
"middleName":"Alli",
"grade":"A",
"kumonLevel":"FK",
"parentId":68,
"userId":1,
"parentBean":{
"parentFirstName":"Alli",
"idParent":68,
"parentMiddleName":"Alli",
"parentLastName":"Alli",
"parentEmailId":"haigopi#gmail.com",
"parentPhoneNumber":"3173797945"},
"startTimeSlot":"12:00 AM",
"endTimeSlot":"12:15 AM",
"dob":"2012-07-04"},
"success":true
}
A student having parentDetails as a seperate object in the above response.
at my client I did the following :
i had a grid with the below configuration :
var studentRecord = Ext.data.Record.create( [ {
name : 'firstName',
type : 'string'
}, {
name : 'lastName',
type : 'string'
}, {
name : 'middleName',
type : 'string'
}, {
name : 'grade',
type : 'string'
}, {
name : 'kumonLevel',
type : 'string'
}, {
name : 'startTimeSlot',
type : 'string'
}, {
name : 'endTimeSlot',
type : 'string'
}, {
name : 'subject',
type : 'string'
}, {
name : 'dob',
type : 'date'
}, {
name : 'status',
type : 'string'
}, {
name : 'paymentOptions',
type : 'string'
}, {
name : 'parentFirstName',
mapping : 'parentBean.parentFirstName',
type : 'string'
}, {
name : 'parentLastName',
mapping : "parentBean['parentLastName']",
type : 'string'
}, {
name : 'parentMiddleName',
mapping : 'parentBean.parentMiddleName',
type : 'string'
}, {
name : 'parentPhoneNumber',
mapping : 'parentBean.parentPhoneNumber',
type : 'String'
}, {
name : 'parentEmailId',
mapping : 'parentBean.parentEmailId',
type : 'string'
} ]);
var myProxy = new Ext.data.HttpProxy( {
method : 'GET',
url : 'listActiveStudents.do'
});
var studentsListReader = new Ext.data.JsonReader( {
successProperty : 'success',
root : 'studentDetails',
idProperty : 'idStudent'
}, studentRecord);
var studentDS = new Ext.data.Store( {
proxy : myProxy,
autoLoad : true,
totalProperty : 'total',
reader : studentsListReader
});
upon data receiving from the server I did the following :
handler : function() {
studentForm.getForm().submit({
url : 'createStudent.do',
waitMsg : 'Saving Data...',
submitEmptyText : false,
success : function(form, action) {
win.close();
var studentDetail = action.result.studentDetails;
var xyz = new studentDS.recordType(studentDetail, 0);
studentDS.insert(0,xyz);
}
});
}
The problem what I am facing here is :
When the record is inserted the parentDetails are not showing up in the grid. Seems, the mapping is not working properly while inserting. Where as while loading the grid initially it renders perfectly. I created the record well which shows in firefox debbuger with valid values too.
could any one guide me please?
This is a very tricky issue. but I found an easy (but dirty) solution, which you just need to edit the line where you create your record, from this:
var xyz = new studentDS.recordType(studentDetail, 0);
to this:
var xyz = new studentDS.recordType(
studentDS.reader.extractValues(
studentDetail,
studentDS.fields.items,
studentDS.fields.length
), studentDetail.idStudent); //use the idStudent of the studentDetail, so the id of the newly created record equals to your idStudent
And here is why
So after tracing the calling stack, I found an interesting differences between the records you loaded from Store, and the record that you created through your new studentDS.recordType.
Look at the differences:
//This is the record created from Store Load event
dob: Wed Jul 04 2012 00:00:00 GMT+0800 (Malay Peninsula Standard Time)
endTimeSlot: "12:15 AM"
firstName: "Alli"
grade: "A"
kumonLevel: "FK"
lastName: "Alli"
middleName: "Alli"
parentEmailId: "haigopi#gmail.com"
parentFirstName: "Alli"
parentLastName: "Alli"
parentMiddleName: "Alli"
parentPhoneNumber: "3173797945"
paymentOptions: "EFT"
startTimeSlot: "12:00 AM"
status: "ACTIVE"
subject: "MATH"
__proto__: Object
//This is the record created from your studentDS.recordType
dob: "2012-07-04"
endTimeSlot: "12:15 AM"
firstName: "Alli"
grade: "A"
idStudent: 80
kumonLevel: "FK"
lastName: "Alli"
middleName: "Alli"
parentBean: Object
idParent: 68
parentEmailId: "haigopi#gmail.com"
parentFirstName: "Alli"
parentLastName: "Alli"
parentMiddleName: "Alli"
parentPhoneNumber: "3173797945"
__proto__: Object
parentId: 68
paymentOptions: "EFT"
startTimeSlot: "12:00 AM"
status: "ACTIVE"
subject: "MATH"
userId: 1
__proto__: Object
In fact, while you load your data, your JsonStore and JsonReader did a dirty hack to your loaded data. They linearize your data. They move all your data from your parentBean to the root of the record.data, so while rendering the grid, your grid can be rendered correctly.
To know how they render your grid, check the code at Line 827 of GridView.js
meta.value = column.renderer.call(column.scope, record.data[column.name], meta, record, rowIndex, i, store);
Notice how the GridView is capturing the values. They use record.data[column.name] to get the value of each fields, and this is where all your parent* report undefined.
And so to know how they linearize your codes, you can check line 157 of DataReader.js
var record = new Record(this.extractValues(n, fi, fl), this.getId(n));
//where:
//n = your raw json object
//fi = the field items
//fl = the field length
And in fact the new Record they used here is identical with your new studentDS.recordType, with the exception that they extractValues for you on behalf, and clearly you did not do it because it's not obvious to do so.
Got it? Hope the explanation is clear enough.