SAP UI5 Json Model Count - javascript

i have the following Problem. Sorry for my bad english that way.
I want to read a jsonfile and count the Number of Persons in it.
This result i will write to an variable.This variable is connected to the TileContainer. So when i write an new entry in my Json File i want that the TileContainer number is increased to.
Here my Code from my Company.json File:
{
"mitarbeiter": [
{ "Lastname": "Mustermann",
"Firstname": "Max",
"icon": "sap-icon://globe",
"adress": "Essen",
"geschlecht": "männlich",
"plz": "42222",
"street": "Viehoferplatz 11",
"jobinfo": "Softwareentwickler"
},
{ "Lastname": "Fischer",
"Firstname": "Elke",
"icon": "sap-icon://globe",
"adress": "Hamburg",
"geschlecht": "weiblich",
"plz": "31441",
"street": "Am Fischmarkt 12",
"jobinfo": "Verwaltungsassistentin"
},
{ "Lastname": "Mustermann",
"Firstname": "Heike",
"icon": "sap-icon://globe",
"adress": "Essen",
"geschlecht": "weiblich",
"plz": "42222",
"street": "Viehoferplatz 11",
"jobinfo": "Vorstandsvorsitzende"
}
]
}
on my controller.js
onInit: function() {
this.getView().addDelegate({onBeforeShow: function(evt) {
if (this.direction != "back") {
var model = new sap.ui.model.json.JSONModel();
model.loadData("JsonModels/Company.json");
alert(model.getJSON());
var XYZ;
var jsonModel =
{
"Tiles":[
{"Tile":
{ id : "idModelTile1",
title : "Mitarbeiter",
info: "Mitarbeiterdaten",
icon:"sap-icon://company-view",
activeIcon:"inbox",
number: XYZ,
appto: "idListPage"
//numberUnit: "positions"
},
}, ......
I want that the variable XYZ gets the Length Value, bevor the TileContainer is rendered. So the Number of Company-Employess is given on the Selectionscreen View.
Hope some one can help me. I make some implementations with jquery and so but nothing really work fine.
Dear,
Christian

When i add
alert(model.getProperty("/mitarbeiter/length"));
i get the alert message "undefined"...

Since the length property of an array can be read, you could simply use
var XYZ = model.getProperty("/mitarbeiter/length");
EDIT: here's a code example for the comment I gave below
onInit: function() {
jQuery.ajax({
url: "JsonModels/Company.json",
dataType: "json",
success: function(data, textStatus, jqXHR) {
var mitarbeiterCount = data.length;
var oTileModel = new sap.ui.model.json.JSONModel();
oTileModel.setData({
tiles :[{
tile : {
id : "idModelTile1",
title : "Mitarbeiter",
info : "Mitarbeiterdaten",
icon :"sap-icon://company-view",
activeIcon:"inbox",
number : mitarbeiterCount,
appto : "idListPage"
},
}]
});
sap.ui.getCore().setModel(oTileModel);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Oh no, an error occurred");
}
});
}
In your view, if you now bind your tile's number property, it should automagically work:
var oTileTemplate = new sap.m.StandardTile({
icon : "{icon}",
number : "{number}",
numberUnit: "mitarbeiter",
title : "{title}",
info : "{info}"
});
var oTileContainer = new sap.m.TileContainer().bindAggregation("tiles", "/", oTileTemplate);
//Etc...

Related

How to fetch internal key value and data in ajax call?

I have tried the following lines of code in jquery
<h5>Marks per Subjects</h5>
<ul id="subjectsMarks">
</ul>
$.ajax({
url: 'index.php?action=fetchStudentIfResultFound',
type: 'POST',
dataType: 'JSON',
...
...
for(i=0; i<data[1].length; i++)
{
$("#subjectsMarks li").html(key[1][i] + ':' + data[1][i]+ "<br/>"+data[1]["Status"]);
}
});
In console data is like
0
:
Object
1
:
Array(4)
0
:
Array(1)
1
:
Array(2)
0
:
Object
Physics
:
"150.00/200"
Status
:
"Pass"
proto
:
Object
1
:
Object
Science
:
"400.00/600"
Status
:
"Pass"
proto
:
Object
...........
I want data in li should look like
Marks per Subjects
Physics: 150.00/200
Status : Pass
Science: 400.00/600
Status: Pass
Please help me !!!
Modify your data from backend and add keys to data as below , it will easy to know where have to loop and don't need to know when to stop
var data: {
student: {
"_id": {
"$id": "5715f58299fbad800100003a"
},
"student_id": 36,
"‌​registration_temp_pe‌​rm_no": "453654",
"rol‌​l_no": "31",
"admissio‌​n_date": "04/12/2016"‌​,
"first_name": "Momin‌​",
"middle_name": "Bas‌​hir",
"last_name": "Ra‌​ther",
"dob": "7/9/199‌​5",
"gender": "Male",
"‌​blood_group": "",
"bir‌​th_place": "",
"nation‌​ality": "",
"language"‌​: "",
"religion": "Isla‌​m"...
},
marks: {
subjects: [
{
"Physic‌​s": "150.00/200",
"Sta‌​tus": "Pass"
},
{
"Scien‌​ce": "400.00/600",
"St‌​atus": "Pass"
}
],
"Tot‌​al Marks": "550/800",
"Grade": "Ist",
}
}
Try loop using below code
//Without modify json from backend
var allSubjects=data[1][1];
//With modify json from backend
var allSubjects=data[1][1]['Sub‌​jects'];
for(var i in allSubjects){
var keysOfObject=Object.Keys(allSubjects[i]);
$("#subjectsMarks li").html(keysOfObject[0] + ':' + allSubjects[i][keysOfObject[0]]+ "<br/>"allSubjects[i]["Status"]);
/* //console.log(allSubjects[i].keysOfObject[0], keysOfObject[0])
console.log(allSubjects[i]);*/
}
2nd version loop
for(var i in allSubjects){
var subject='';
for(var key in allSubjects[i]){
subject=key;
break;
}
//var keysOfObject=//Object.Keys(allSubjects[i]);
$("#subjectsMarks li").html(subject + ':' + allSubjects[i][subject]]+ "<br/>"allSubjects[i]["Status"]);
console.log(allSubjects[i][subject], subject)
}

Parse JSON in Jquery with an API

I am trying to cancel all my listings on Bitskins, but they have a weird system where each listing is unique, even if its for the same item. Meaning my 88 pages of listings is an absolute pain to remove.
So I thought of going the autohotkey route, but my end goal is to actually use the API to create specific listings. So I wrote a little test script/link.
https://bitskins.com/api/v1/cancel_buy_order/?api_key=myapikey&code=mycode&buy_order_id=995544
It worked. I proceeded to make a html with a javascript linked to it, but to spam the link 8 times a second with a decreasing number of id ultimately did not work. The browser would just crash.
Then I realized I can make a little script and run it on the site.
var id = 995544;
function loop() {
setTimeout(function () {
id--;
$.ajax({
url: '/api/v1/cancel_buy_order',
type: 'post',
data: {
api_key: $('#apiKey').text(),
buy_order_id: id
},
});
loop();
}, 1000);
}
loop();
While this works, it would take me 11.5 days to remove all listings. Partially because the delay is 1 second as opposed to 1000/8. (The api only allows 8 request a second.) But the biggest reason would be because it attempts to remove listings that don't even exist.
What I mean by this is, Each by listing has a random increment after the last one (e.g. 994488 -> 994502 -> 994503 and so on).
I needed a way to find the buy order id, and then use it in the second code I put here.
var id = (function () {
var id = null;
$.ajax({
'async': false,
'global': false,
'url': '/api/v1/get_active_buy_orders',
type: 'get',
data: {
api_key: 'myapikey',
code: 'mycode',
},
dataType: 'json',
success: function (data){
id = data
}
});
return id;
console.log(id);
})();
This thankfully works, but unfortunately it does not parse the
"data" : {
"orders" : [
parts of the JSON.
While I would love not to ask how to parse the JSON on here and find the answer for myself, I'm either googling the wrong thing, or am too dumb to understand how to do it.
So my question is, how would I parse JSON in JQuery?
{
"status" : "success",
"data" : {
"orders" : [
{
"buy_order_id" : 503154,
"market_hash_name" : "P2000 | Pulse (Field-Tested)",
"price" : "0.03",
"suggested_price" : "0.14",
"state" : "LISTED",
"created_at" : 1454390518,
"updated_at" : 1454390518,
"settled_with_item" : null
},
],
"page" : 88
}
}
if you want to get all buy_order_ids from JSON try the following snippet
x = {
"status": "success",
"data": {
"orders": [{
"buy_order_id": 503154,
"market_hash_name": "P2000 | Pulse (Field-Tested)",
"price": "0.03",
"suggested_price": "0.14",
"state": "LISTED",
"created_at": 1454390518,
"updated_at": 1454390518,
"settled_with_item": null
}, {
"buy_order_id": 502154,
"market_hash_name": "P2000 | Pulse (Field-Tested)",
"price": "0.03",
"suggested_price": "0.14",
"state": "LISTED",
"created_at": 1454390518,
"updated_at": 1454390518,
"settled_with_item": null
}, ],
"page": 88
}
}
var ids = x.data.orders.map(function(d) {
return d.buy_order_id
})
document.write('<pre>' + JSON.stringify(ids, 0, 4) + '</pre>')

Construct new array based on lastChangedDate

I have a refreshdata() function which executes a call to get IDs of certain events:
function refreshdata()
{
$http({
url: “…/GetIDs”,
method: "POST",
data: jsonData,
dataType: "json",
timeout: 7000,
contentType: 'application/json; charset=utf-8'
}).success(function(data, status, headers, config) {
responseNew=data.d;
meetings = JSON.parse(responseNew);
console.log("Got meetings");
meetingsanddetails(meetings);
}).error(function(data, status, headers, config) {
alert("Unable to refresh data.”);
});
}
meetings is something like:
{
"Result":"success",
"Key":"12345",
"Data":[
{"ID":"GFDCV34","lastChangedDate":"2015-12-03 11:14:27"},
{"ID":"IDJHE23","lastChangedDate":"2015-12-03 15:17:47"},
{"ID":"KDJBD34","lastChangedDate":"2015-12-03 05:25:11"}
]
}
Next, I do meetingsanddetails(meetings):
res = meetings;
var i = 0;
var tmp = [];
promises = [];
res.Data.map(function (val) {
promises.push(getdetails2(val.ID).then(function (data) {
tmp = JSON.parse(data);
Object.keys(tmp.Data[0]).map(function (v, j) {
val[v] = tmp.Data[0][v];
});
}, function (error) {
console.log(error)
}));
});
$q.all(promises).then(function () {
$timeout(function () {$ionicLoading.hide()}, 500);
$window.localStorage['data'] = JSON.stringify(res);
});
res is now something like:
{
"Result": "success",
"Key": "12345",
"Data":[
{
"ID": "GFDCV34",
"name": "Name of event 1",
"date": "date of event 1",
"location": "location of event 1",
"lastChangedDate": "2015-12-03 11:14:27"
},
{
"ID": "IDJHE23",
"name": "Name of event 2",
"date": "date of event 2",
"location": "location of event 2",
"lastChangedDate": "2015-12-03 15:17:47"
},
{
"ID": "KDJBD34",
"name": "Name of event 3",
"date": "date of event 3",
"location": "location of event 3",
"lastChangedDate":"2015-12-03 05:25:11"
}
]
}
(credit to maurycy)
(Info: getdetails2(id) returns the details of an event with a given ID).
This works fine, but the getdetails2 calls take a long time to load. That is way I would like to make it work like this:
If …/GetIDs returns IDs that weren’t already in $window.localStorage['data'], they should be added with their details.
The IDs that …/GetIDs returns that were already in $window.localStorage['data’], should only be updated if the lastChangedDate of the new call is more recent.
IDs that are present in $window.localStorage['data’], but not in the new call, should be deleted.
Anyone who can point me in the right direction? I keep messing up this array hocus pocus.
First of all, don't rely on localStorage: in private mode in Safari it does not work, so you need to have some fallback to prevent errors.
What you want to achieve is a caching thing. You have two possibilities: do it on your own which would take some time and probably will have some bugs (I did it couple of times and it was not fun at all) or use ready solutions, e.g. this advanced angular-cache. It allows to choose the storage type, can be natively used with $http / $resource and allows operations with the cache such as deleting cached responses (that's what you would need to do when you get a newer timestamp). It is quite easy to use, just check the docs and examples.

Loading JSON into timemap

I want to load a JSON into a timemap, and my code seems to be missing something to configure the JSON correctly. JSON format below
{"results": [{"Lat": "34.0453113", "text": "Historic Core DTLA",
"Lon": "-118.2501836", "bicyclistCount": "26", "date": "2014-10-15"},
{"Lat": "34.0444899", "text": "Spring # 7", "Lon": "-118.2523059",
"bicyclistCount": "16", "date": "2014-10-26"}]}
This link contains the html file based mainly on a timemap example. It opens up the timeline and map, but the data does not load. Also the map won't zoom in and out, though I want to solve the JSON load issue first. Do you have a suggestion on what I can change? Adding the JavaScript code below. Thanks, Patty
The JavaScript code:
var tm;
var errFn = function(jqXHR, textStatus, errorThrown){
alert(textStatus);
}
$(function() {
tm = TimeMap.init({
mapId: "map", // Id of map div element (required)
timelineId: "timeline", // Id of timeline div element (required)
options: {
eventIconPath: "../images/"
},
datasets: [
{
title: "JSON String Dataset",
type: "json",
options: {
// json file
url: "output.json", <!--this file sits in the same folder as the HTML-->
error: errFn,
}
}
],
bandIntervals: [
Timeline.DateTime.DAY,
Timeline.DateTime.WEEK
]
});
<!--start loading data-->
function transformData(data) {
var text, Lat, Lon, bicyclistCount, date; <!--is this how the data is called?-->
var newData = {
"title" : text,
"start" : date,
"options" : {
"description" : bicyclistCount
}
};
newData["point"] = {
"lat" : Lat,
"lon" : Lon,
};
}
});
<!--end loading data-->
If you don't want to change json then define custom loader and configure Timemap to use it.
$(function() {
TimeMap.loaders.custom = function(options) {
var loader = new TimeMap.loaders.remote(options);
loader.parse = JSON.parse;
loader.preload = function(data) {
return data["results"]
}
loader.transform = function(data) {
return {
"title" : data.text,
"start" : data.date,
"options" : {
"description" : data.bicyclistCount
},
"point": {
"lat" : data.Lat,
"lon" : data.Lon,
}
};
};
return loader;
};
tm = TimeMap.init({
mapId: "map", // Id of map div element (required)
timelineId: "timeline", // Id of timeline div element (required)
options: {
eventIconPath: "../images/"
},
datasets: [
{
title: "JSON String Dataset",
type: "custom",
options: {
// json file
url: "output.json"
}
}
],
bandIntervals: [
Timeline.DateTime.DAY,
Timeline.DateTime.WEEK
]
});
});
I see a javascript error on your page: Uncaught TypeError: undefined is not a function on this line: data.forEach(function(item)
data is an Object, not an Array
Object
results: Array[10]
Change your JSON from:
{"results": [{"Lat": "34.0453113", "text": "Historic Core DTLA", "Lon": "-118.2501836", "bicyclistCount": "26", "date": "2014-10-15"}, {"Lat": "34.0444899", "text": "Spring # 7", "Lon": "-118.2523059", "bicyclistCount": "16", "date": "2014-10-26"}]}
To:
[{"Lat": "34.0453113", "text": "Historic Core DTLA", "Lon": "-118.2501836", "bicyclistCount": "26", "date": "2014-10-15"}, {"Lat": "34.0444899", "text": "Spring # 7", "Lon": "-118.2523059", "bicyclistCount": "16", "date": "2014-10-26"}]
(make it an array not an object with an array as its "results" property)
Change your JSON Format to:
[
{
"title":"example",
"start":"1968-10-12",
"end": "1968-11-12",
}
]

Getting error " Uncaught SyntaxError: Unexpected identifier " during fetching a json file

I want to get data from a json file, the json file is accessing but i am getting this error (Uncaught SyntaxError: Unexpected identifier) at console. The error line is at the success function.
What is the error I can not understand.
Please help me.
Thanks in advance.
My code sample is below
var Book = Backbone.Model.extend({
defaults:{
"id": "aaaa",
"name" : "bbbbb",
"title" : "cccc"
}
});
var Books = Backbone.Collection.extend({
model: Book,
});
var Allbooks = new Books();
Allbooks.fetch({
url: "book.json",
dataType:'json',
contentType:'application/json'
success:function() {
console.log(Allbooks);
},
error: function(){
console.log('error in loading and processing the JSON file');
}
});
my json file(book.json) is below
[{
"id": "aaaa3",
"name" : "bbbbb3",
"title" : "cccc3",
},{
"id": "aaaa1",
"name" : "bbbbb1",
"title" : "cccc1",
},{
"id": "aaaa2",
"name" : "bbbbb2",
"title" : "cccc2",
}];
Is should be
success:function(response) {
console.log(response);
}
You need a comma at the end of the previous line to continue the object.
Allbooks.fetch({
url: "book.json",
dataType:'json',
contentType:'application/json', // <<< that's where it was missing
success:function() {
console.log(Allbooks);
},
error: function(){
console.log('error in loading and processing the JSON file');
}
In addition to the previous answers, your json is invalid too. json should look like this
[{
"id": "aaaa3",
"name": "bbbbb3",
"title": "cccc3" << removed comma from here
}, {
"id": "aaaa1",
"name": "bbbbb1",
"title": "cccc1" << removed comma from here
}, {
"id": "aaaa2",
"name": "bbbbb2",
"title": "cccc2" << removed comma from here
}]

Categories

Resources