Json.getproperty giving undefined - javascript

I have the following code where I need do draw a table using sap ui5 JSON Model. When I run the program I'm getting no data in the output table. I json.getProperty alert I'm getting alert output as undefined.
<!DOCTYPE html>
<html>
<head>
<!-- Load UI5, select gold reflection theme and the "commons" and "table" control libraries -->
<script id="sap-ui-bootstrap"
type="text/javascript"
src="https://sapui5.netweaver.ondemand.com/resources/sap-ui-core.js"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-libs="sap.ui.commons,sap.ui.table"></script>
<script>
jQuery.ajax({
url: "/XMII/Illuminator?QueryTemplate=ZTest/QueryTemplates/table%20list&content-type=text/json",
dataType: "json",
success: function(data, textStatus, jqXHR) { // callback called when data is received
var jsonModel = new sap.ui.model.json.JSONModel();
jsonModel.loadData(data);
sap.ui.getCore().setModel(jsonModel);
var weatherTable = new sap.ui.table.Table({
title : "Current Weather Details",
visibleRowCount : 20
});
weatherTable.addColumn(new sap.ui.table.Column({
label : new sap.ui.commons.Label({text : "Tablename"}),
template : new sap.ui.commons.TextView().bindText("TableName")
}));
var oModel1 = new sap.ui.model.json.JSONModel();
var aData = jsonModel.getProperty("/Rowsets/Rowset/Row");
oModel1.setData({modelData : aData});
weatherTable.setModel(oModel1);
weatherTable.bindAggregation("rows","/modelData");
weatherTable.placeAt('content');
var dataLayout = new sap.ui.layout.HorizontalLayout({
id : "dataLayout", // sap.ui.core.ID
});
var Tablename = new sap.ui.commons.TextView({
id : "Tablename",
text : '{TableName}'
})
dataLayout.addContent(Tablename);
dataLayout.placeAt("content");
}
});
</script>
</head>
<body class='sapUiBody'>
<div id='content'></div>
</body>
</html>

Related

How display JSON output in html page using JQuery?

This is how I made API request using Python request :
mainurl = 'http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/'
api_key = '9420'
fields = '?fields=productId,productUrl,productTitle,salePrice,originalPrice,imageUrl'
payload = {
'keywords': "women",
'pageSize': "40",
'language': 'en',
'sort': 'volumeDown',
'isFreeShip': 'y',
'isFavorite': 'y',
'pageNo': "1"
}
urlx = mainurl + api_key + fields
r = requests.get(urlx, params=payload)
print(r.content)
when run it returns long JSON outputs :
{'result': {'commissionRate': '5.00%', 'originalPrice': 'US $1.21', ......}, 'currentPageNum': 0, 'errorCode': 20010000, 'totalPageNum': 0}
and this is how I try to make an API request using JQuery :
## index.html ##
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="orders">
</div>
<script src="js/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script src="js/main.js" type="text/javascript" charset="utf-8" async defer></script>
</body>
</html>
## main.js ##
$(function (){
var $orders = $('#orders');
$.ajax({
type: 'GET',
url: 'http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/9420?fields=productUrl,originalPrice,productTitle&keywords=women',
success: function(orders){
$.each(orders, function(i, order){
$orders.append('<li> products :' + order.totalResults + '</li>');
});
}
});
});
I got this result in my browser :
products :5291514
This is the JSON output :
{"result":{"totalResults":5275965,"products":[{"productTitle":"S-XL Plus Size Tunic Autumn ...}
How can display productTitle in my html page ?
If I understood the question well, this is what you wanted to show?
$.each(orders, function(i, order){
$orders.append('<li> products :' + order.products[0].productTitle + '</li>');
});

How to display API data using Ajax?

I want to be able to use the API from the code below to display data in a formatted way such as this example.
Job Title: Agricultural and Related Trades
Percentage of Occupancies in Area: 15.41%
You can find my poor attempt to display the data below. I am very new to Ajax, jQuery, JavaScript, etc.
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(function() {
$.ajax({
url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
type: "get",
dataType: "json",
success: function(data) {
console.log(data[0].area);
outputString= data[0].description.percentage;
var paragraph = $("<p />", {
text: outputString
});
$("body").append(paragraph);
}
});
});
</script>
After successfully execute your GET request you will get your response at data variable now you can run a for loop to populate your expected outcome 'HTML' TEXT
than you can append it on your HTML body
I have used here JavaScript toFixed() Method keeping only two decimals
$(function() {
$.ajax({
url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
method: "GET",
dataType: "json",
success: function(data) {
var str = "";
for(var i= 0; i < data.jobsBreakdown.length; i++){
str +='Job Title : '+data.jobsBreakdown[i].description+' and Related Trades <br> Percentage of Occupancies in Area : '+data.jobsBreakdown[i].percentage.toPrecision(2)+'% <br><br>';
}
$("body").html(str);
}
});
});
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Something like this is likely what you want:
<script>
$(function() {
$.ajax({
url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
type: "get",
dataType: "json",
success: function(data) {
data.jobsBreakdown.forEach(function(job) {
var job_text = "Job Title: " + job.description;
var percentage_text = "Percentage of Occupancies in Area: " + job.percentage.toFixed(2) + "%"
$("body").append("<div style='margin-bottom: 10px;'><div>" + job_text + "</div><div>" + percentage_text + "</div></div>")
})
}
});
});
</script>
You can use string templates to create your paragraph content.
Use the <br /> HTML element to make a new line in the paraghraph.
let data = [{
area: 'Agricultural and Related Trades',
percentage: 15.41
}]
var paragraph = document.createElement('p');
paragraph.innerHTML = `Job Title: ${data[0].area}<br/>
Percentage of Occupancies in Area: ${data[0].percentage}%"`;
document.body.appendChild(paragraph);
You need to define a function to render a single item of description and percentage.
For parsing the percentage, you can use Number object
When you get the data back from Ajax, you need to loop on the items and pass each one of them to your render function you defined earlier (here I used forEach).
Generally, as rule of thumb, you have to split your code into functions each with single responsibility.
function renderItem(itemData) {
const title = $('<p/>').text('Job Title: ' + itemData.description);
const percentage = $('<p/>').text('Percentage of Occupancies in Area: '+ new Number(itemData.percentage).toFixed(2) + '%');
const item = $('<li/>').append(title, percentage);
$('#result').append(item);
}
$(function() {
$.ajax({
url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
type: "get",
dataType: "json",
success: function(data) {
data.jobsBreakdown.forEach(renderItem);
}
});
});
Job Title: Agricultural and Related Trades
Percentage of Occupancies in Area: 15.41%
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="result"></ul>

on click event I am trying to get the data from XML as per the click object's attr() value

on click event I am trying to get the data from XML as per the click object's attr() value.
Below I have placed two hyperlink buttons and a container for input the data. Both are having different attr() value.
So I want to get the data according to these hyperlink's attr() value.
Even I have created a XML with respective nodes.But unable to get the exact data. can anyone please help?
here is the JS and XML code:
JS Code:
$(function() {
$('a.readmore').click(function() {
var container = $('#uiWrapper');
$.get('myxml3.xml',function(data){
container.empty();
$(data).find('sector').each(function(){
var $tag = $(this),
getName = $('a.readmore').attr('href');
var html = '<div class="data">';
html += '<div class="tagDetail">' + $tag.find('description').text() + '</div>';
html += '</div>';
if($tag.attr('name') == getName){
container.append(html);
}else{
return false;
}
});
});
return false;
});
});
XMLCode:
<?xml version="1.0" encoding="utf-8" ?>
<sections>
<sector name="mark">
<description>Mark Text is coming</description>
</sector>
<sector name="source">
<description>Source Text is coming</description>
</sector>
</sections>
If you want by clicking on the link the description is display according to the href attribute of the link, your html page with script will be
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var container = $('#uiWrapper');
$('a.readmore').click(function(e){
e.preventDefault();
var getName=$(this).attr('href')
container.empty();
$.get('myxml3.xml', function(xml){
$(xml).find('sector').each(function(){
var $sector = $(this);
var title = $sector.attr("name");
if(title===getName){
var description = $sector.find('description').text();
var html='<div class="data"><div class="tagDetail">'+description+'</div></<div>'
$('#uiWrapper').append($(html));
};
});
});
});
});
</script>
</head>
<body>
<div id="uiWrapper"></div>
<a class="readmore" href="mark">mark</a>
<a class="readmore" href="source">source</a>
</body>
</html>
For this example i use the xml file of your post
If you want to get the same result by using the $ajax method, your code will be
<script type="text/javascript">
$(document).ready(function(){
var container = $('#uiWrapper');
$('a.readmore').click(function(e){
e.preventDefault();
var getName=$(this).attr('href')
container.empty();
$.ajax({
type: "GET",
url: "myxml3.xml",
dataType: "xml",
success: function (xml) {
var xmlDocument = $.parseXML(xml)
var $xml = $(xmlDocument);
$(xml).find('sector').each(function(){
var $sector = $(this);
var title = $sector.attr("name");
if(title===getName){
var description = $sector.find('description').text();
var html='<div class="data"><div class="tagDetail">'+description+'</div></<div>'
$('#uiWrapper').append($(html));
}
})
}
});
});
});
</script>

How to parse json using sapui5

I am currently parsing json and displaying the data in a table control using sapui5,but i am unable to parse inner objects values
CODE:
<!DOCTYPE html>
<html><head>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<title>Table example</title>
<!-- Load UI5, select gold reflection theme and the "commons" and "table" control libraries -->
<script id='sap-ui-bootstrap' type='text/javascript'
src='resources/sap-ui-core.js'
data-sap-ui-theme='sap_goldreflection'
data-sap-ui-libs='sap.ui.commons,sap.ui.table'></script>
<script>
// create the DataTable control
var oTable = new sap.ui.table.Table({editable:true});
// define the Table columns
var oControl = new sap.ui.commons.TextView({text:"{comments/data/from/username}"}); // short binding notation
oTable.addColumn(new sap.ui.table.Column({label: new sap.ui.commons.Label({text: "Group"}), template: oControl }));
var oControl = new sap.ui.commons.TextView({text:"{comments/data/from/id}"}); // short binding notation
oTable.addColumn(new sap.ui.table.Column({label: new sap.ui.commons.Label({text: "Group Text"}), template: oControl }));
var oModel = new sap.ui.model.json.JSONModel();
var aData =
jQuery.ajax({
url: "https://api.instagram.com/v1/media/popular?client_id=d6ff37e000de4fc7882e4e5fccfff236", // for different servers cross-domain restrictions need to be handled
dataType: "json",
success: function(data, textStatus, jqXHR) { // callback called when data is received
var JsonData = data;
oModel.setData(JsonData); // fill the received data into the JSONModel
alert("sparta");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("error");
}
});
// create a JSONModel, fill in the data and bind the Table to this model
// oModel.setData(aData);
oTable.setModel(oModel);
oTable.bindRows("/data");
// finally place the Table into the UI
oTable.placeAt("content");
</script>
</head>
<body class='sapUiBody'>
<div id='content'></div>
</body>
</html>
How do i fetch the inner element values such as username and id etc..
Try something like
var oControl = new sap.ui.commons.TextView().bindProperty("text", "user/usernme");
oTable.addColumn(new sap.ui.table.Column({label: new sap.ui.commons.Label({text: "User Name"}), template: oControl}));
var oControl = new sap.ui.commons.TextView().bindProperty("text", "user/id");
oTable.addColumn(new sap.ui.table.Column({label: new sap.ui.commons.Label({text: "UserID"}), template: oControl}));
https://sapui5.hana.ondemand.com/sdk/#docs/guide/JSONModel.html
var arr = oModel.getData();
Using this you get the data for that model, then you can loop through the data or parse it.

How can I trigger a Dojo xhrGet by clicking instead of on page load?

New to Dojo Toolkit, I'm able to successfully get an xhrGet to load on page load but I need to load the xhrGet when a row of a DataGrid is selected. Is there even a way to do so?
<!doctype html>
<html>
<head>
<script type="text/javascript>
dojo.connect(btn, "onclick", function() {
/************************/
/* xhr - AJAX functions */
/************************/
dojo.ready(function(){
var targetNode = dojo.byId("xhr-container");
var xhrArgs = {
url: "info-to-get.html",
handleAs: "text",
load: function(data){
targetNode.innerHTML = data;
},
error: function(error){
targetNode.innerHTML = "You messed up, dummy!: " + error;
}
}
var deferred = dojo.xhrGet(xhrArgs);
});
});
</script>
</head>
<body>
<button type="button" id="btn">TEST</button>
<br>
<br>
<div id="xhr-container"></div>
</body>
</html>
The xhrGet works fine by itself on page load, no dice when trying to call it through a button.
This will wire up the click of an html domNode to firing a function where you can put your xhr code.
dojo.connect(someDomNode, 'onclick', function() {
//xhr code here
});
If it is a widget, like dijit.form.Button you can write
dojo.connect(someWidget, 'onClick', function() {
//xhr code here
});
--EDIT ----------------------
Based on your posted code, I would expect the following to work:
dojo.ready(function(){
var targetNode = dojo.byId("xhr-container");
var fnDoXHR = function() {
var xhrArgs = {
url: "info-to-get.html",
handleAs: "text",
load: function(data){
targetNode.innerHTML = data;
},
error: function(error){
targetNode.innerHTML = "You messed up, dummy!: " + error;
}
};
var deferred = dojo.xhrGet(xhrArgs);
};
dojo.connect(dojo.byId('btn'), 'onclick', fnDoXHR);
});

Categories

Resources