Javascript to render charts not working with .getJSON - json

Correction: /devicedata to /products - that was a typo..
I have built a node-express app which I am using to to plot a graph from the data retrieved from mongo database. I have tried two external libraries Chart.js and Canvas.js. Both work perfectly fine when the data is hard-coded in the javascript. The moment I use $.getJSON to retrieve the data from database it stops working. On the server side code is as below:
app.get('/products', function(req, res) {
var db = req.db;
db.collection('products').find().toArray(function (err, items) {
res.json(items);
});
});
On the client side code is as below:
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/products", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "Temperatures recorded this year"
},
data: [
{
type: "column",
dataPoints: result,
}
]
});
chart.render();
});
});
</script>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
Is there an alternative to .getJSON to retrieve data from database (mongo in this case) ? The chart is rendering as a blank canvas

Related

Setting up the Header Using Http to get the Json file

I do have a working table using JSON and angular, I set up my $http header to get the Json in the particular .api, I run it but nothings appear in getting my Json file in the $Http.get, I would like to ask if this is a valid header, I mean is there something wrong with my delimeter?
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.0/angular.min.js"></script>
<script type="text/javascript">
var myTable=angular.module('myTable',[]);
myTable.controller('tableCtrl',function($scope,$http){
$http.get ("http://staging.api.sample.com/events.json", {header: {Authorization: 'vsdnmsndjednmsdnjemsdjendmsdnjeNmJHMN'}}); .success(function(response) {
debugger
$scope.members=response.events;
$scope.totals = response.paging;
});
});
Remember about correct style guide. It should help you. Also check this link https://github.com/johnpapa/angular-styleguide/
(function {
'use strict';
angular
.module('myTable', [])
.controller('tableCtrl', tableCtrl);
tableCtrl.$inject = ['$scope', '$http'];
function tableCtrl($scope, $http) {
$http.get("http://staging.api.sample.com/events.json", {
header: {
Authorization: 'vsdnmsndjednmsdnjemsdjendmsdnjeNmJHMN'
}
}).then(function(response.data) {
$scope.members = response.data.events;
$scope.totals = response.data.paging;
}).catch(function(error) {
});
});
}());
This query is wrong:
$http.get("http://staging.api.sample.com/events.json", {
header: {
Authorization: 'vsdnmsndjednmsdnjemsdjendmsdnjeNmJHMN'
}
}
You can pass parametes by get building query like this one:
$http.get("http://staging.api.sample.com/customer/1") or
$http.get("http://staging.api.sample.com/customer/" + some_param). If you would like to send some object to you API you should use POST. For example:
$http.post("http://staging.api.sample.com/events.json", {object});

IBM Worklight JSONStore - Add and get data

I am using worlight JSONstore. I am new to it. I tried searching that read all docs but didn't get much idea.
I have one login page from that I get some json data I want to store that data using jsonstore. and get that afterwards.
I made jsonstore adapter.
Json-Store-Impl.js
function getJsonStores(custData) {
var data = custData;
return data;
//custdata is json
}
function addJsonStore(param1) {
var input = {
method : 'put',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
function updateJsonStore(param1) {
var input = {
method : 'post',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
function deleteJsonStore(param1) {
var input = {
method : 'delete',
returnedContentType : 'json',
path : 'userInputRequired'
};
return WL.Server.invokeHttp(input);
}
after that I Create a local JSON store.
famlCollection.js
;(function () {
WL.JSONStore.init({
faml : {
searchFields: {"response.mci.txnid":"string","response.mci.scrnseqnbr":"string","response.loginUser":"string","request.fldWebServerId":"string","response.fldRsaImageHeight":"string","request.fldRequestId":"string","request.fldTxnId":"string","response.fldDeviceTokenFSO":"string","response.fldRsaCollectionRequired":"string","response.datlastsuccesslogin":"string","response.fldRsaUserPhrase":"string","response.fldRsaAuthTxnId":"string","response.rc.returncode":"string","response.datcurrentlogin":"string","response.mci.deviceid":"string","response.customername":"string","request.fldDeviceId":"string","response.fldRsaUserStatus":"string","request.fldScrnSeqNbr":"string","response.fldRsaImageWidth":"string","request.fldLangId":"string","response.fldTptCustomer":"string","response.encflag":"string","response.rc.errorcode":"string","response.fldRsaImagePath":"string","response.mci.appid":"string","response.mci.requestid":"string","response.rc.errormessage":"string","response.mci.appserverid":"string","response.fldRsaCollectionType":"string","request.fldAppId":"string","response.fldRsaImageId":"string","request.fldLoginUserId":"string","response.mci.sessionid":"string","response.mci.langid":"string","response.mci.remoteaddress":"string","request.fldAppServerId":"string","response.mci.webserverid":"string","response.fldRsaImageText":"string","response.fldRsaEnrollRequired":"string","response.fldRsaActivityFlag":"string"},
adapter : {
name: 'JsonStore',
replace: 'updateJsonStore',
remove: 'deleteJsonStore',
add: 'addJsonStore',
load: {
procedure: 'getJsonStores',
params: [],
key: 'faml'
},
accept: function (data) {
return (data.status === 200);
}
}
}
}, {
password : 'PleaseChangeThisPassword'
})
.then(function () {
WL.Logger.debug(['Take a look at the JSONStore documentation and getting started module for more details and code samples.',
'At this point there is no data inside your collection ("faml"), but JSONStore is ready to be used.',
'You can use WL.JSONStore.get("faml").load() to load data from the adapter.',
'These are some common JSONStore methods: load, add, replace, remove, count, push, find, findById, findAll.',
'Most operations are asynchronous, wait until the last operation finished before calling the next one.',
'JSONStore is currently supported for production only in Android and iOS environments.',
'Search Fields are not dynamic, call WL.JSONStore.destroy() and then initialize the collection with the new fields.'].join('\n'));
})
.fail(function (errObj) {
WL.Logger.ctx({pretty: true}).debug(errObj);
});
}());
When I clicked on login button I call getJsonStores like this -
getJsonStores = function(){
custData = responseData();
var invocationData = {
adapter : "JsonStore",
procedure : "getJsonStores",
parameters : [custData],
compressResponse : true
};
//WL.Logger.debug('invoke msg '+invocationData, '');
WL.Client.invokeProcedure(invocationData, {
onSuccess : sucess,
onFailure : AdapterFail,
timeout: timeout
});
};
I followed these steps
Is this right way? and how can I check jsonstore working locally or not? and how can I store my jsondata in JSONStore? Where should I initialize the wlCommonInit function in project?
plz Help me out.
Open main.js and find the wlCommonInit function, add the JSONStore init code.
WL.JSONStore.init(...)
You already have an adapter that returns the data you want to add to JSONStore, call it any time after init has finished.
WL.Client.invokeProcedure(...)
Inside the onSuccess callback, a function that gets executed when you successfully get data from the adapter, start using the JSONStore API. One high level way to write the code would be, if the collection is empty (the count API returns 0), then add all documents to the collection.
WL.JSONStore.get(collectionName).count()
.then(function (countResult) {
if(countResult === 0) {
//collection is empty, add data
WL.JSONStore.get(collectionName).add([{name: 'carlos'}, {name: 'mike'}])
.then(function () {
//data stored succesfully
});
}
});
Instead of adding [{name: 'carlos'}, {name: 'mike'}] you probably want to add the data returned from the adapter.
Later in your application, you can use the find API to get data back:
WL.JSONStore.get(collectionName).findAll()
.then(function (findResults) {
//...
});
There is also a find API that takes queries (e.g. {name: 'carlos'}), look at the getting started module here and the documentation here.
It's worth mentioning that the JSONStore API is asynchronous, you must wait for the callbacks in order to perform the next operation.

Request.JSON run with page load

http://mootools.net/demos/?demo=Request.JSON
The JSON data load when you click on load JSON Data .
Is it possible to load this data when a page open ( a function like onload )
<head>
<script type="text/javascript">
window.addEvent("domready",function(){
var request = new Request.JSON({
url: '/echo/json/',
onRequest: function(){
gallery.set('text', 'Loading...');
},
onComplete: function(jsonObj) {
gallery.empty();
addImages(jsonObj.previews);
},
data: { // our demo runner and jsfiddle will return this exact data as a JSON string
json: JSON.encode(data)
}
}).send();
});
</script>
</head>

Getting static data from a json file into backbone model

I have the following code and was wondering why my data isn't getting pulled into my model? I'm using a static json file and I'm guessing this might be my problem but can't seem to find any documentation about it.
var DataModel = Backbone.Model.extend({
initialize: function () {
console.log('initiliazed model')
},
url: "data/data.json"
});
var StructureView = Backbone.View.extend ({
initialize: function () {
console.log('initiliazed view')
_.bindAll(this);
this.model.fetch();
this.render();
this.model.on('change',this.render);
},
el : '#ev-wrapper',
render: function () {
$('#ev-wrapper').empty().append(Handlebars.compile($('#ev-template').html())(this.model.toJSON()));
$('.ev-asset-loader').fadeOut('slow');
}
});
var structureView = new StructureView({model: new DataModel()});
You need to call fetch. This will issue an AJAX request using url
var model = new DataModel();
model.fetch();
Open Firebug or your favorite browser's network console to see AJAX requests and check if it's OK

Completely wipe out the dijit (dojo) tree from memory and free its placeholder

I begin with piece by piece of code so that the problem description becomes clear.
I have a piece of HTML code as:
<div id="center" class="column" dojoType="dijit.layout.TabContainer">
<div id="first" dojoType="dijit.layout.ContentPane" title="first" selected="true">
<div id="first_content"></div>
</div>
<div id="second" dojoType="dijit.layout.ContentPane" title="second">
<div id="second_content"></div>
</div>
</div>
I have a javascript function to load the dijit trees into HTML :
function load()
{
//load data
dojo.xhrGet(firsthierarchy("first_content", "file1.json"));
dojo.xhrGet(secondhierarchy("second_content", "file2.json"));
}
function firsthierarchy(node, url){
return {
url: url,
node: dojo.byId(node),
handleAs: "json",
load: loadfirsthierarchy
};
}
function secondhierarchy(node, url){
return {
url: url,
node: dojo.byId(node),
handleAs: "json",
load: loadsecondhierarchy
};
}
function loadfirsthierarchy(data, xhr)
{
if(xhr.args.node)
{
store1 = new dojo.data.ItemFileWriteStore({data: data});
treeModel1 = new dijit.tree.ForestStoreModel({
store: store1,
query: {
"type": "continent"
},
rootId: "root",
rootLabel: "Continents",
childrenAttrs: ["children"]
});
tree1 = new dijit.Tree({
model: treeModel1,
},xhr.args.node.id);
}
}
function loadsecondhierarchy(data, xhr)
{
if(xhr.args.node)
{
store2 = new dojo.data.ItemFileWriteStore({data: data});
treeModel2 = new dijit.tree.ForestStoreModel({
store: store2,
query: {
"type": "continent"
},
rootId: "root",
rootLabel: "Continents",
childrenAttrs: ["children"]
});
tree2 = new dijit.Tree({
model: treeModel2,
},xhr.args.node.id);
}
}
All of the above functions are working fine. Now, I want to have a reset function such that it can wipe out the existing trees in the "first_content" and "second_content" div and load those divs with new trees having new content. Eg:
function reset()
{
// here I want to completely wipe out the exiting trees in all of the dojo contentpanes.
// And I want to load the contentpanes with entire new set of data.
// Maybe like :
// dojo.xhrGet(firsthierarchy("first_content", "file3.json"));
// dojo.xhrGet(secondhierarchy("first_content", "file4.json"));
}
I have no idea on how to implement the reset function. Could you please provide me a clue.
Keep references to the tree, treeModel and store, then define your function as:
reset: function() {
myTree.destroyRecursive();
myTreeModel.destroyRecursive(); // I'm not 100% sure you need this, destroying the tree may do this automatically
delete myStore
}
That should do the trick
The way I'd do this is to create a module using dojo.provide called TreeWrapper() which handles the Tree lifecycle (fetching the data, creating the tree, killing the tree). This wrapper module then has the reset function above and can contain references to all the different variables.
You'll also need to keep track of any dojo.subscribe's you have for the tree and unsubscribe from those.