how to update existing json object in java script with titanium studio - json

var args = arguments[0] || {};
$.atn.text=args.attendance;
Ti.API.info('attendance:'+args.attendance);
function doClick(e){
$.atn.value=$.atn.value+1;
Ti.API.info('atn is'+$.atn.value);
var url = "api.usergrid.com/PRI_95616/LOGIN/attendances?";
var client = Ti.Network.createHTTPClient({
onload : function(e) {},
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
},
timeout : 5000 // in milliseconds
});
client.setRequestHeader('content-type', 'JSON');
client.open("PUT", url);
client.send(JSON.stringify(jsonobject));
}
I want to fetch and then update the attendance value then insert the updated value in database. How can I do it?

If by "update the database" you mean PUT to the Restful API, then you have one small error.
client.send(JSON.stringify(jsonobject));
jsonobject is not defined. It must be the json (JavaScript) object you just built. if $.atn is the object you're pushing values into then try:
client.send(JSON.stringify($.atn));
I don't know the REST API specs for usergrid.com, but if all you have to do is PUT a json object with .text and .value defined, the URL "api.usergrid.com/PRI_95616/LOGIN/attendances?" then this should do it. However, you'll have to put http:// before the URL like:
"http://api.usergrid.com/PRI_95616/LOGIN/attendances?"

Related

Microsoft cognitive services face API call

I've build an application on the Azure (microsoft) emotion API, but that was just merged with their cognitive services face API. I'm using a webcam to send an image (in binary data) to their server for analysis, and used to get an xml in return. (I've already commented out some old code, in this example. Trying to get it fixed).
function saveSnap(data){
// Convert Webcam IMG to BASE64BINARY to send to EmotionAPI
var file = data.substring(23).replace(' ', '+');
var img = Base64Binary.decodeArrayBuffer(file);
var ajax = new XMLHttpRequest();
// On return of data call uploadcomplete function.
ajax.addEventListener("load", function(event) {
uploadcomplete(event);
}, false);
// AJAX POST request
ajax.open("POST", "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=emotion","image/jpg");
ajax.setRequestHeader("Content-Type","application/json");
//ajax.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml");
ajax.setRequestHeader("Ocp-Apim-Subscription-Key","subscription_key");
ajax.send(img);
}
now I understood from their website the call returns a JSON. But I just can't get it to work. I can see there is data coming back, but how do I even get the JSON out of it. I'm probably missing something essential, and hope someone can help me out. :) the program was working when I could still use the Emotion API.
function uploadcomplete(event){
console.log("complete");
console.log(event);
//var xmlDoc = event.target.responseXML;
//var list = xmlDoc.getElementsByTagName("scores");
console.log(JSON.stringify(event));
A few issues to address:
You'll want to wait for the POST response, not just for the upload
completion.
You'll want to set the content type to be application/octet-stream if you are uploading a binary as you are.
You'll want to set the subscription key to the real value (you probably did before pasting your code here.)
.
function saveSnap(data) {
// Convert Webcam IMG to BASE64BINARY to send to EmotionAPI
var file = data.substring(23).replace(' ', '+');
var img = Base64Binary.decodeArrayBuffer(file);
ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == XMLHttpRequest.DONE) {
console.log(JSON.stringify(ajax.response));
}
}
ajax.open('post', 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=emotion');
ajax.setRequestHeader('Content-Type', 'application/octet-stream');
ajax.setRequestHeader('Ocp-Apim-Subscription-Key', key);
ajax.send(img);
}

Data not being fetched from json file

I am trying to fetch data from the static json file but the data is not getting displayed at all. What could be the possible reason for it.
Below is my code:
var Collection = Backbone.Collection.extend({
url: "names_of_people.json",
initialize: function() {
this.fetch();
}
});
collections = new Collection();
console.log("the length "+collections.length);
for (i=1;i<collections.length;i++)
{
console.log("done "+ collections.at(i).get("name"));
}
The problem is that this code:
console.log("the length "+collections.length);
for (i=1;i<collections.length;i++)
{
console.log("done "+ collections.at(i).get("name"));
}
ends up being executed before this.fetch() has completed. You'll need to either put your code in this.fetch's success callback, like this:
var Collection = Backbone.Collection.extend({
url: '/data.json',
initialize: function() {
this.fetch({
success: function() {
console.log(collections, 'the length ' + collections.length);
for (var i = 0; i < collections.length; i++) {
console.log('done ' + collections.at(i).get('name'));
}
}
});
}
});
var collections = new Collection();
or by listening to the collection's sync event, which occurs when this.fetch has completed successfully. This pattern is more commonly used in Backbone applications.
var Collection = Backbone.Collection.extend({
url: '/data.json',
initialize: function() {
this.listenTo(this, 'sync', this.syncExample);
this.fetch();
},
syncExample: function() {
console.log(collections, 'the length ' + collections.length);
for (var i = 0; i < collections.length; i++) {
console.log('done ' + collections.at(i).get('name'));
}
}
});
var collections = new Collection();
You can read more about Backbone's event system and the listenTo function here.
check backbone parse function. after fetch it will also call vlidate and parse if they exist.
EDIT: more detail
The key thing here I think is, the fetch() is asynchronous, so by the time you start loop, the data is not here yet. So you need to execute the code when you are sure the collection is ready. I usually listen to a "reset" event, and let the fetch to fire a reset event by collection.fetch({reset:true}).
Backbone Collection, whenever fetch, and get an array of data from server in a format
[obj1,obj2],
it will pass each of these into a parse function, described here
For debug purpose you can simply do:
var MyCollection=Backbone.Collection.extend({
parse:function(response){
console.log(response);
return response;
}
})
This can check if the fetch indeed get the json.
On a side note, it is always a good practise to fetch it after you initialized the collection, means you don't put the this.fetch() inside initialize(), you do this outside.
for example, if you want to print out all the element name, you can do
var c=MyCollection();
c.fetch({reset:true}); // this will fire 'reset' event after fetch
c.on('reset',printstuff());
function printstuff(){
_.forEach(c,function(e){
console.log(e.get('name'));
});
}
Note this 'reset' event fires after all the collection is set, means it is after the parse() function. Apart from this parse(), there is also a validate function that is called by model. You collection must have a model parameter, you can make your own model, and give it a validate(), it also print out stuff.

SAPUI5 get single property from JSON-Model

I am currently trying to figure out how I can retrieve a single value from a sap.ui.model.json.JSONModel
in my main view:
var gConfigModel = new sap.ui.model.json.JSONModel();
var getConfigCallback = function(config) {
gConfigModel.setData(config);
};
oController.getConfiguration(getConfigCallback);
console.log(gConfigModel);
in my controller:
getConfiguration : function(callback) {
var sServiceUrl = "/sap/opu/odata/sap/xxx/ConfigurationSet('Initialize')";
var config = {};
callback(config);
$.getJSON(sServiceUrl).done(function(data) {
config = data.d;
callback(config);
});
},
In my console.log statement I can see that the data was successfully passed from the backend and successfully set to the JSON model. My requirement is to store the value of attribute Editable in a single variable.
I already tried gConfigModel.getProperty('/'), didnt work. tried to access gConfigModel.oData was undefined .. How can I store it in a single value?
Solution Comment: If you catch data from a backend, you have to take care how long it takes. data can be available later then expected, in my case I added 1s timeout, afterwards I can access the property easily
setTimeout(function() {
console.log(gConfigModel.getProperty('/Editable'));
}, 1000);
I wouldn't advise using the model's getData() method since it is deprecated.
A much better solution is to use gConfigModel.getProperty("/Editable")
(I'm using the root slash here since your property resides in the root of your model)
In the same way, you can also set your data:
gConfigModel.setProperty("/Editable", <your new value>) instead
First of all, thanks for the effort to find solutions of our Problems! (at least, those regarding It stuff.. :) )
I've found a solution which I think is a little bit more save because the timeout is maybe somewhat arbitrary - it would depend on the machine or the amount of data that is to be fetched?
Therefore, I am using an attachRequestCompleted function:
with sUrl_2="path-to-my-service";
var oModel_2 = new sap.ui.model.json.JSONModel(sUrl_2);
oModel_2.attachRequestCompleted(function(data) {
//now, i can access the data stored in the oModel_2, either by getProperty, or by DOM: oModel_2.oData.d.Vendor
gv_selLieferant = oModel_2.getProperty("/d/Vendor");
gv_selEinkOrg = oModel_2.getProperty("/d/PurchOrg");
gv_selEinKGru = oModel_2.getProperty("/d/PurGroup");
});
<script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-theme="sap_bluecrystal" data-sap-ui-libs="sap.m"></script>
<script>
function getConfiguration(callback) {
var sServiceUrl = "/sap/opu/odata/sap/xxx/ConfigurationSet('Initialize')";
var config = {};
var data = {
"d": {
"_metadata": "",
"Backup01": "01",
"Editable": "True"
}
};
setTimeout((function() {
config = data;
callback(config);
})(), 2000);
};
var gConfigModel = new sap.ui.model.json.JSONModel();
var getConfigCallback = function(config) {
gConfigModel.setData(config);
alert(gConfigModel.getProperty("/d/Editable"));
};
getConfiguration(getConfigCallback);
</script>

How to create an object of specific type from JSON in Parse

I have a Cloud Code script that pulls some JSON from a service. That JSON includes an array of objects. I want to save those to Parse, but using a specific Parse class. How can I do it?
Here's my code.
Parse.Cloud.httpRequest({
url: 'http://myservicehost.com',
headers: {
'Authorization': 'XXX'
},
success: function(httpResponse) {
console.log("Success!");
var json = JSON.parse(httpResponse.text);
var recipes = json.results;
for(int i=0; i<recipes.length; i++) {
var Recipe = Parse.Object.extend("Recipe");
var recipeFromJSON = recipes[i];
// how do i save recipeFromJSON into Recipe without setting all the fields one by one?
}
}
});
I think I got it working. You need to set the className property in the JSON data object to your class name. (Found it in the source code) But I did only try this on the client side though.
for(int i=0; i<recipes.length; i++) {
var recipeFromJSON = recipes[i];
recipeFromJSON.className = "Recipe";
var recipeParseObject = Parse.Object.fromJSON(recipeFromJSON);
// do stuff with recipeParseObject
}
Example from this page https://parse.com/docs/js/guide
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
score: 1337,
playerName: "Sean Plott",
cheatMode: false
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
}
});
IHMO this question is not a duplicate of How to use Parse.Object fromJSON? [duplicate]
In this question the JSON has not been generated by the Parse.Object.toJSON function itself, but comes from another service.
const object = new Parse.Object('MyClass')
const asJson = object.toJSON();
// asJson.className = 'MyClass';
Parse.Object.fromJSON(asJson);
// Without L3 this results into:
// Error: Cannot create an object without a className
// It makes no sense (to me) why the Parse.Object.toJSON is not reversible

Binding JSON string to ListView in Metro apps?

I have a metro application(HTML5 & WinJS) in which am trying to display service data . Actually here am retrieving JSON data from my service but am unable to bind this data into listview . Anyone give me some working example.
Thank you.
You can use the WinJS.xhr() for this. You can read more about it on this link https://msdn.microsoft.com/pt-br/library/windows/apps/br229787.aspx and here is an example:
var path = "data/file.json";
function getData(path) {
WinJS.xhr({ url: path }).then(
function (response) {
var json = JSON.parse(response.responseText);
// Since this is an asynchronous function, you can't
// return the data, so you can:
// 1) retrieve the data to a namespace once the app loads.
var list = new WinJS.Binding.List(json);
Somenomespace.data = list;
// 2) or do all the binding inside the function.
var listView = document.getElementById("listViewID");
listView.winControl.itemDataSource = list.dataSource;
});
}
If you use the built in JSON.parse(jsonString) function you can loop through the content using a normal for loop as it then is a normal object and add it as usuall. Just remember to process or render the data.
Her is an example from code i had in a search page using listview:
var response = JSON.parse(data) ;
var originalResults = new WinJS.Binding.List();
for (x in response) {
originalResults.push(response[x]);
}
this.populateFilterBar(element, originalResults);
this.applyFilter(this.filters[0], originalResults);