Calling a JSON function from a module in Dojo - json

The contents of my dataHelper.js file:
define(["dojo/_base/declare", "dojo/dom", "dojo/_base/xhr", "dojo/json"],
function(declare, dom, xhr, json){
return {
getJSON: function(){
xhr.get({
url: "../../cpuusage.json",
handleAs: "json",
load: function(jsonData){
return jsonData;
},
error: function() {
}
});
}
};
});
I'm trying to run this from my index.html as follows:
var chartData = dataHelper.getJSON();
I think I have several issues. First of all, I'm not sure my module and the getJSON function is defined correctly. Secondly I get errors on my console:
TypeError: this.source is undefined
[Break On This Error]
= [],
dojo.js (line 362)
SyntaxError: missing : after property id
},
dojo.js (line 330)
SyntaxError: missing : after property id
},
dojo.js (line 330)
SyntaxError: missing : after property id
},
All I want to achieve first is load the json data into the chartData variable. Many thanks.

The first issue I'm seeing is you are treating an asynchronous process as if it was a synchronous one. The xhr.get returns immediately after the request to the server is sent, it does not block until a response is received.
First, I would add a console.log to your module definition to ensure that your dataHelper module is being loaded correctly.
define(["dojo/_base/xhr"],
function(xhr){
console.log('dataHelper.js loaded');
return {
//
};
});
Also note that above you aren't using any of the base dojo modules except dojo/_base/xhr, so it is unnecessary to include them (unless they are used outside this snippet).
You need to update your code to handle this call asynchronously. To do this, you could take advantage of the fact that the xhr.get method returns a Deferred object. This class makes dealing with asynchronous in a consistent manner quite easy.
To do this, update the dataHelper module to return the result of the xhr call:
define(["dojo/_base/xhr"], function(xhr){
return {
getJSON: function(){
//this returns a Deferred object, what to do on load and error is then handled by the invoker
return xhr.get({
url: "../../cpuusage.json",
handleAs: "json"
});
}
};
});
Then, when utilizing this module:
//replace dataHelper with whatever it's path is
require(['dataHelper'],function(dataHelper){
var deferred = dataHelper.getJSON();
deferred.then(function(data){
//this function is invoked once the data has been fully loaded
}, function(error){
//this function is invoked if an error occurs while loading the data (in case of a server error response or if the response isn't in the format you specified)
});
});

This is my proposal:
Your dataHelper.js file:
define("dataHelper", ["dojo/_base/declare", "dojo/dom", "dojo/_base/xhr"],
function(declare, dom, xhr){
return declare("dataHelper", [], {
getJSON: function(){
return xhr.get({
url: "../../cpuusage.json",
handleAs: "json"
});
});
};
});
your invocation:
require(["dataHelper"], function(dataHelper) {
var chartData;
dataHelper.getJSON().then(function(jsonData) {
chartData = jsonData;
//Continue doing stuff with chartData in here, not outside
});
});

Related

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.

Backbone.js Service Call Event Binding

I'm new to Backbone, and I am trying to do a get request (getDivisions) and store the response JSON into 'divisions', defined in my defaults. I logged 'divisions' inside the service call, and outside the service call, as seen below.
define(['underscore', 'backbone', 'service-manager', 'backbone-nested'],
function(_, Backbone, svgmgr) {
return Backbone.NestedModel.extend({
defaults: {
message: "",
divisions: []
},
initialize: function () {
this.getDivisions();
},
getDivisions: function() {
var that = this;
svgmgr.Interface.call('getDivisions').done(function(data) {
that.set('divisions', data);
console.log("Inside the service call: " + that.get('divisions'));
});
console.log("Outside service call" + this.get('divisions'));
}
});
});,
In Dev Tools, the 'Outside the service call' log was called first, returning a blank array (it's default), while the 'Inside the service call' log was called after that, returning the correct response data. This is obviously not what I want.
How do I get this model to run this service call on initialize, so that when I reference 'divisions' I get back the response data?
First you don't need a Model but a Collection, and second Backbone can handle the ajax call for you.
So you have to do like this :
var Division = Backbone.Model.extend({
urlRoot: /* url to get a single division */,
defaults: {...}
});
var Divisions = Backbone.Collection.extend({
url: /* url to get all your divisions */,
model: Division,
initialize: function () {
this.fetch({
success: function(response) {
// you get the result here
}
});
}
});

AngularJS with Jersey JSON resource in undefined in javascript

This is weird issue I have so far.
I am using jaxon backbone to do this Angularjs project.
java resource file
#GET #Path("{query}")
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Signature findByName(#PathParam("query") String query) {
return dao.findById(query);
}
control.js file
function SearchCtrl($rootScope,$scope,Signature) {
// console.log('SearchCtrl is invoked!!!!!!');
$scope.signature;
$scope.searcherrormsg='';
$scope.searchaction = function(barcodenum,signature) {
signature = Signature.query({rewardcardId:barcodenum});
$scope.signature = signature;
alert("data is " + $scope.signature.name); <=== This is UNDEFINED
};
}
apps.js file
angular.module('demo', ['demo.filters', 'demo.directives','demo.services.signature']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/search', {templateUrl: 'partials/search.html', controller: SearchCtrl});
$routeProvider.otherwise({redirectTo: '/search'});
service.js file
angular.module('demo.services.signature', ['ngResource']).
factory('Signature', function($resource){
return $resource('api/signature/:rewardcardId', {}, {
query: {method:'GET', params:{rewardcardId:'signature'}, isArray:false}
});
});
This is invoking database and server console is showing the following message ;
com.sun.jersey.api.container.filter.LoggingFilter$Adapter finish
INFO: 1 * Server out-bound response
1 < 200
1 < Content-Type: application/json
1 <
{"name":"xxx xxxx","customerid":187,"email":"xxxx#hotmail.com","sign":null,"barcode":"xxxx"}
And it displays return data at the HTML page properly. For example, the html page has
<p>{{signature.barcode}}
{{signature.name}}
which are displaying name and barcode properly as the above data set .
It only has an issue to get the data from the javascript that is saying undefined.
Whenever the javascript is trying to get the data from return resources from database, it is saying undefined.
You are trying to print the resource before it is available. The request to the server is asynchronous. Put alert("data is " + $scope.signature.name); in the success callback instead.
$scope.searchaction = function (barcodenum, signature) {
Signature.query({ rewardcardId: barcodenum },
function(data) {
$scope.signature = data;
alert("data is " + $scope.signature.name);
},
function(err) { // error handling can go here
});
};
I am not sure why you pass signature to $scope.searchaction and then perform an assignment operation on it.

Callback function in dojo.io.script.get

I am trying to get some JSON from an external url. This works fine with the twitter request in the example in the dojo documentation.
I guess the problem comes with the callback function, as I'm not sure if I need one and where to place it.
The JSON looks like:
{"upcoming":[]}
and that's how I call it:
function getJSON(){
// Look up the node we'll stick the text under.
var targetNode = dojo.byId("results");
// The parameters to pass to xhrGet, the url, how to handle it, and the callbacks.
var jsonpArgs = {
url: url,
load: function(data){
console.log(data);
// Set the data from the search into the viewbox in nicely formatted JSON
targetNode.innerHTML = "<pre>" + dojo.toJson(data, true) + "</pre>";
},
error: function(error){
targetNode.innerHTML = "An unexpected error occurred: " + error;
}
};
test = dojo.io.script.get(jsonpArgs);
}
dojo.ready(getJSON);
ant that's the output I get:
JSON:
{
"returnValue": true,
"timeStamp": 1332858447300,
"eventPhase": 0,
"target": null,
"defaultPrevented": false,
"srcElement": null,
"type": "load",
"cancelable": false,
"currentTarget": null,
"bubbles": false,
"cancelBubble": false
}
Are you referring to this statement in your example?
// The parameters to pass to xhrGet, the url, how to handle it, and the callbacks.
If so, the "callbacks" are the load and error functions.

Help using Mootools and JSONP

I am having a really hard time trying to get this to work. All I require is to console log the object that is returned. I see nothing at all in the log although the script tag is getting injected into the head.
JSON:
jsonFeed({
"results":{
"loggedin": "No",
"username": "",
"company": ""
}
});
JS:
function jsonFeed() {
}
window.addEvent('domready', function() {
new Request.JSONP({
url: <correcturl>,
onComplete: function(data){
console.log(data); // Nothing returned
}
}).send();
});
Any help is greatly appreciated.
UPDATE
I have removed the jsonFeed function at the top and changed the existing code to:
new Request.JSONP({
log: true,
url: loginstatus,
callbackKey: 'jsonFeed',
onComplete: function(data){
console.log(data); // Nothing returned
}
}).send();
In the log I get:
JSONP retrieving script with url:http://thedomain/LoggedStatus.aspx?jsonFeed=Request.JSONP.request_map.request_0
jsonFeed is not defined
In the this gets injected:
<script type="text/javascript" async="true" src="http://thedomain/LoggedStatus.aspx?jsonFeed=Request.JSONP.request_map.request_0">
-- if I expand this I see the JSON --
</script>
so a) I'm getting the jsonFeed not defined error and b) the onSuccess isn't firing :(
I really do appreciate all your help guys. And I am sorry if I am missing the point :(
UPDATE
added:
this.jsonFeed = function(data) {
console.log(data);
};
.. and it works. Thank you #Dimitar
I still don't quite understand it but now it works it helps when working it out.
it does not work because your callback function name ignores the one that Request.JSONP sends and returns jsonFeed instead.
http://mootools.net/docs/more/Request/Request.JSONP
callbackKey (string: defaults to callback) the key in the url that the server uses to wrap the JSON results. So, for example, if you used callbackKey: 'callback' then the server is expecting something like http://..../?q=search+term&callback=myFunction; This must be defined correctly.
here's an example class i wrote that gets stuff off of flickr - who use a custom callback key - it's fine. http://fragged.org/mootools-flickr-api-class-via-request-jsonp_1042.html (p.s. jsfiddle may be slow atm, friday 13th thing!)
the other thing is, if the remote end CONTINUES not to work with you and refuses to send data in the correctly wrapped format, eg:
Request.JSONP.request_map.request_0({data})
then you need to actually make sure that
this.jsonFeed = function(data) {
console.log(data);
};
where this is the global object (eg, window) - you cannot scope this, so careful where the function is defined.
if doing the latter, jsonFeed will then take the role of a callback oncomplete function.
another way is to do this, which will map the native callback function defined by the class and export it to the one your remote host likes:
onRequest: function() {
var lastCallback;
Object.each(Request.JSONP.request_map, function(el) {
lastCallback = el;
});
window.jsonFlickrApi = lastCallback;
},
onComplete: function(data) {
...
}
jsonFeed(
return //or anything else that will make this piece of data recognizable on your page
{
"results":{
"loggedin": "No",
"username": "",
"company": ""
}
});
new Request.JSONP({
url: <correcturl>,
callbackKey: 'jsonFeed'
onComplete: function(data){
console.log(data); // Nothing returned
}
}).send();