SAPUI5 oData V4 Read Object - json

How to read the object in UI5 with oData V4?
Basically I want to get the JSON object from the URL service:
Ths is my onInit function in the controller.
onInit: function() {
var this_ = this;
this.getView().addEventDelegate({
onBeforeShow: function(evt) {
var oModel = new sap.ui.model.json.JSONModel();
oModel = sap.ui.getCore().getModel("appid");
var app_id = oModel.getData().app_id;
this_.getView().bindElement({
path: "zearnModel>/zearn_summary(" + app_id + ")"
});
}
});
}

From the documentation:
The OData V4 model only supports data access using bindings. It does not provide any direct access to the data.
To get the raw JSON object, all you can do is use jQuery's ajax features to request the data:
$.get({
url: "<your_service_url>/zearn_summary(" + app_id + ")",
success: function(data) {
// your success logic
},
error: function(error) {
// your error logic
}
});

Related

ajax returning json data as undefined

when i run below code.
it makes error and alert "fail error:StntaxError: Unexpected token < in JSON at position 0 data:undefined"
what is the problem ??
$("#a").click(function () {
st_dt = $("#st_dt").val();
end_dt = $("#end_dt").val();
lot_cd = $("#lot_cd").val();
var obj = { st_dt: st_dt, end_dt: end_dt, lot_cd: lot_cd };
var json_1 = JSON.stringify(obj);
$.ajax({
type: "POST",
url: '{{ url_for("get_operid") }}',
data: json_1,
dataType: "JSON",
success: function (data) {
alert("Success\n" + data);
},
error: function (request, status, error, data) {
alert("fail\n" + "error:" + error + "\n data:" + data);
}
});
});
Looking at the code it looks like a Laravel API request using Blade Template or the Function url_for is in Flask... In either case
That means the response for the api request is HTML string instead of
a json response...
i.e. The API request is returning a login page or some HTML page...
To check the response you can open the Chrome Devtools in the Network tab check the response of the API...
what you can try is :
var obj = { st_dt: st_dt, end_dt: end_dt, lot_cd: lot_cd };
console.log(obj);
var json_1 = JSON.stringify(obj);
console.log(json_1);
Then See in browser console what is your object and if the JSON converting your object properly.
If that is ok , Your request should be done currectly. And try to see what are the data you getting as response with:
success: function (data) {
consoel.log('response below');
console.log(data);
}
You will find the error. I hope.

CouchDb 2.1.1 Admin API Compaction PUT Request

I am working in NodeJS with CouchDB 2.1.1.
I'm using the http.request() method to set various config settings using the CouchDB API.
Here's their API reference, yes, I've read it:
Configuration API
Here's an example of a working request to set the logging level:
const http = require('http');
var configOptions = {
host: 'localhost',
path: '/_node/couchdb#localhost/_config/',
port:5984,
header: {
'Content-Type': 'application/json'
}
};
function setLogLevel(){
configOptions.path = configOptions.path+'log/level';
configOptions.method = 'PUT';
var responseString = '';
var req = http.request(configOptions, function(res){
res.on("data", function (data) {
responseString += data;
});
res.on("end", function () {
console.log("oldLogLevel: " + responseString);
});
});
var data = '\"critical\"';
req.write(data);
req.end();
}
setLogLevel();
I had to escape all the quotes and such, which was expected.
Now I'm trying to get CouchDb to accept a setting for compaction.
The problem is that I'm attempting to replicate this same request to a different setting but that setting doesn't have a simple structure, though it appears to be "just a String" as well.
The CouchDB API is yelling at me about invalid JSON formats and I've tried a boatload of escape sequences and attempts to parse the JSON in various ways to get it to behave the way I think it should.
I can use Chrome's Advanced Rest Client to send this payload, and it is successful:
Request Method: PUT
Request URL: http://localhost:5984/_node/couchdb#localhost/_config/compactions/_default
Request Body: "[{db_fragmentation, \"70%\"}, {view_fragmentation, \"60%\"}, {from, \"23:00\"}, {to, \"04:00\"}]"
This returns a "200 OK"
When I execute the following function in my node app, I get a response of:
{"error":"bad_request","reason":"invalid UTF-8 JSON"}
function setCompaction(){
configOptions.path = configOptions.path+'compactions/_default';
configOptions.method = 'PUT';
var responseString = '';
var req = http.request(configOptions, function(res){
res.on("data", function (data) {
responseString += data;
});
res.on("end", function () {
console.log("oldCompaction: " + responseString);
});
});
var data = "\"[{db_fragmentation, \"70%\"}, {view_fragmentation, \"60%\"}, {from, \"23:00\"}, {to, \"04:00\"}]\"";
req.write(data);
req.end();
}
Can someone point at what I'm missing here?
Thanks in advance.
You need to use node's JSON module to prepare the data for transport:
var data = '[{db_fragmentation, "70%"}, {view_fragmentation, "60%"}, {from, "23:00"}, {to, "04:00"}]';
// Show the formatted data for the requests' payload.
JSON.stringify(data);
> '"[{db_fragmentation, \\"70%\\"}, {view_fragmentation, \\"60%\\"}, {from, \\"23:
00\\"}, {to, \\"04:00\\"}]"'
// Format data for the payload.
req.write(JSON.stringify(data));

Wrong data format for store loadData method ExtJS

I want to call JSON data as much as the amount of data in the store. Here is the code:
storeASF.each(function(stores) {
var trano = stores.data['arf_no'];
Ext.Ajax.request({
results: 0,
url: '/default/home/getdataforeditasf/data2/'+trano+'/id/'+id,
method:'POST',
success: function(result, request){
var returnData = Ext.util.JSON.decode(result.responseText);
arraydata.push(returnData);
Ext.getCmp('save-list').enable();
Ext.getCmp('cancel-list').enable();
},
failure:function( action){
if(action.failureType == 'server'){
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Error!', obj.errors.reason);
}else{
Ext.Msg.alert('Warning!', 'Server is unreachable : ' + action.response.responseText);
}
}
});
id++;
});
storeARF.loadData(arraydata);
StoreASF contains data[arf_no] which will be used as a parameter in Ajax request url. StoreASF could contain more than one set of the object store, so looping is possible. For every called JSON data from request would be put to array data, and after the looping is complete, I save it to storeARF with the loadData method.
The problem is, my data format is wrong since loadData can only read JSON type data. I already try JSON stringify and parse, but couldn't replicate the data format. Any suggestion how to do this? Thank you.
Rather than using Ext.util.Json.decode(), normalize the data in success() method using your own logic. For example:
success: function (response) {
console.log(response);
var myData = [];
Ext.Array.forEach(response.data, function (item) {
myData.push({
name: item.name,
email: item.email,
phone: item.phone
});
});
store.load();
}

Backbone - parsing JSON ID

I'm trying to parse JSON data using Backbone from a remote API. Here's what I've got so far:
// --------------------------------------------------
// MODELS
// --------------------------------------------------
var VideoModel = Backbone.Model.extend({
idAttribute: '_id',
parse: function(){
this.id = response._id;
}
});
var videoModel = new VideoModel({ parse:true });
// --------------------------------------------------
// COLLECTIONS
// --------------------------------------------------
var VideosCollection = Backbone.Collection.extend({
model: VideoModel,
url: 'redacted',
parse: function(response){
this.videos = response.data;
this.cid = response.cid;
return response.data;
},
render: function(){
this.collection.forEach(this.addone, this);
}
});
var videosCollection = new VideosCollection();
videosCollection.fetch({
success: function(videos){
console.log('success!');
},
error: function(){
console.log('failed.');
}
});
// --------------------------------------------------
// VIEWS
// --------------------------------------------------
var VideoView = Backbone.View.extend({
template: _.template('<%= videoModel.id %>'),
render: function(){
this$el.html(this.template(this.model.attributes));
return this;
}
});
var videoView = new VideoView({});
var VideosCollectionView = Backbone.View.extend({});
var videosCollectionView = new VideosCollectionView({
collection: videosCollection,
render: function(){
this.collection.forEach(this.addOne, this);
},
addOne: function(videoModel){
this.$el.append(videoView.el);
}
});
What I'm having trouble with is that console.log(videoModel.id) is still undefined.
The data is a playlist of videos, which is valid JSON:
{
"total":24,
"per_page":24,
"current_page":1,
"last_page":1,
"from":1,
"to":24,
"data":[
{
"_id":"55d1bb50140ba04c1d8b4583",
Be glad for some prompts in the right direction - especially since I had it working this morning and then ... reverted to a previous version without saving.
Thanks
From documentstion of parse method:
The function is passed the raw response object, and should return the
attributes hash to be set on the model. The default implementation is
a no-op, simply passing through the JSON response.
So by default it works like this:
parse: function(data) {
return data;
}
Your code now returns nothing and model takes no data.
As I see you want to set id attribute but you already have setted idAttribute property with _id and there is _id in your data so it should work fine without parse at all. Try to remove it.
The answer is that I was trying to parse via a Collection instead of a Model. So I would never have got the id I was looking for. For some reason.
I needed to move the URL into the Model and parse from there:
var VideoModel = Backbone.Model.extend({
idAttribute: '_id',
url: 'redacted',
parse: function(response){
var id = response._id;
var cid = response.cid;
return response.data;
},
}),
Now when I do videoModel.get(1) in the console, it returns the value of the first item in my array.

Grails GET method for JSON

I am trying to use the http GET method to retrieve JSON object I have created, then in Titanium I have created a method to retrieve, however it is only retrieving "undefined"
def listJSON() {
def converter = User.list() as JSON
System.out.println(converter)
render(converter)
//response(converter)
}
The output from grails is correct and the page rendered (from system out) :
[{"class":"testingmobile.User","id":1,"age":22,"email":"test#hotmail.com","name":"Ryan","occupation":"Whatever "}]
The code from the mobile app in Titanium is as follows:
var url = "http://localhost:8080/TestingMobile/user/listJSON";
var client = Ti.Network.createHTTPClient ({
onload : function(e) {
Ti.API.info("Recieved text: "+ this.responceText);
var jsonObj = JSON.parse(this.responseText);
getShow(jsonObj);
alert('success');
},
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
},
timeout : 5000
});
client.open("GET", url);
client.send();
The console outputs "Received text: undefined"
responceText
should be
responseText
with an s, not a c.