XML Application String cant be displayed - javascript

The Sting "Fahrzeugnummer" in "Fahrten: All other strings in "Fahrten" are working fine. Just "Fahrzeugnummer" can't be displayed.
Table
<table style="width:100%" id="fahrten-tabelle"></table>
Script
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "https://start.vag.de/dm/api/v1/fahrten.xml/Bus?timespan=100", true);
xmlhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table = "<tr><th>Fahrzeugnummer</th><th>Linie</th></tr>";
var x = xmlDoc.getElementsByTagName("Fahrt");
for (i = 0; i < x.length; i++) {
//Problem:
var fznr = x[i].getElementsByTagName("Fahrzeugnummer")[0] ? x[i].getElementsByTagName("Fahrzeugnummer")[0].childNodes[0].nodeValue : "";
table += "<tr><td>" +
//Problem:
fznr +
"</td><td>" +
x[i].getElementsByTagName("Linienname")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("fahrten-tabelle").innerHTML = table;
}
</script>
Thanks.

To get the value use innerHTML and not nodeValue.
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table = "<tr><th>Fahrzeugnummer</th><th>Linie</th></tr>";
var x = xmlDoc.getElementsByTagName("Fahrt");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" + x[i].childNodes[0].innerHTML + "</td><td>" + x[i].childNodes[1].innerHTML + "</td></tr>";
}
document.getElementById("fahrten-tabelle").innerHTML = table;
}
here's a demo
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "https://start.vag.de/dm/api/v1/fahrten.xml/Bus?timespan=100", true);
xmlhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table = "<tr><th>Fahrzeugnummer</th><th>Linie</th></tr>";
var x = xmlDoc.getElementsByTagName("Fahrt");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" + x[i].childNodes[0].innerHTML + "</td><td>" + x[i].childNodes[1].innerHTML + "</td></tr>";
}
document.getElementById("fahrten-tabelle").innerHTML = table;
}
<body onload="loadXMLDoc()">
<table style="width:100%" id="fahrten-tabelle"></table>
</body>

Related

Names are not displaying on the HTML according to JSON Parse

I am trying to display name on the HTML page as list items pulling it from JSON placeholder It is not displaying on the page.
var request = new XMLHttpRequest();
request.open('GET', 'https://jsonplaceholder.typicode.com/comments');
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var items = JSON.parse(request.responseText);
var str = "<ul>"
for (var i = 0; i < items.lenght; i++) {
str = str + "<li>" + items[i].name + "</li>"
}
console.log(str);
str = str + "</ul>"
document.getElementById("data").innerHTML = str;
}
}
request.send();
no error display
The only problem I can see in here is the typo of the array items.
Try to change it to length.
var request = new XMLHttpRequest();
request.open('GET', 'https://jsonplaceholder.typicode.com/comments');
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var items = JSON.parse(request.responseText);
var str = "<ul>"
for (var i = 0; i < items.length; i++) {
str = str + "<li>" + items[i].name + "</li>"
}
console.log(str);
str = str + "</ul>"
document.getElementById("data").innerHTML = str;
}
}
request.send();
In your code the major problem was that the typo items.length in for loop.
<html>
<div id="data"></div>
<script>
var request = new XMLHttpRequest();
request.open('GET', 'https://jsonplaceholder.typicode.com/comments',true);
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var items = JSON.parse(request.responseText);
var str = "<ul>"
for (var i = 0; i < items.length; i++) {
str = str + "<li>" + items[i].name + "</li>"
}
str = str + "</ul>"
document.getElementById("data").innerHTML = str;
}
}
request.send();
</script>
</html>

Fetching data from two API to merge them in one table

First of all,
you can see below, my working program to fetch Data from two different APIs in two different tables.
First table contains the data from an API : {Cycle, Delegated Stack, Share, expected payment}
The second one gets the data from another API to get : {the cycle, paid reward}
https://codepen.io/alexand92162579/pen/arJqmv?editors=1010
The second Code pen is the same thing but I want to merge the two tables according to the value of the cycle:
https://codepen.io/alexand92162579/pen/OGdjLJ?editors=1011
According to what I read online, I need to use Promises. I have tried this multiple times but never succeeded to make it work !
To try it, enter the Key KT19www5fiQNAiqTWrugTVLm9FB3th5DzH54 in the inputbox.
I will make a donation of 30xtz if someone helps me on this one.
// Fonction to fetch the data for every cycle on the first API
// Data Recolted (Cycle, Balance, Share, Expected Reward, Fee, Status)
// Try to merge with the second table according to the value of cycle
// // KT19www5fiQNAiqTWrugTVLm9FB3th5DzH54 */
function calculate2() {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { table: "cycle", limit: 10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
var KT1 = $('#KT1').val();
console.log(KT1);
xmlhttp.onreadystatechange = function() {
Qfee = 0.08;
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table><tr bgcolor=#000000 color=White>"
txt += "<th>Cycle</th>"
txt += "<th>Balance</th>"
txt += "<th>Share</th>"
txt += "<th>Reward</th>"
txt += "<th>Fee</th>"
txt += "<th>Status</th>"
txt += "</tr>"
for (x in myObj) {
cycle = myObj[x].cycle;
balance = myObj[x].balance/1000000;
TotalReward = myObj[x].rewards/1000000;
status = myObj[x].status.status;
stakingBalance = myObj[x].staking_balance/1000000;
Share = balance/stakingBalance*100;
Fee = Share*TotalReward*Qfee/100;
DelegatorReward = Share*TotalReward/100 - Fee;
txt += "<tr>";
txt += "<td width=10% align=center>" + cycle + "</td>";
txt += "<td width=25% align=center>" + Math.round(balance*100)/100 + "</td>";
txt += "<td width=10% align=center>" + Math.round(Share*10)/10 + " %" + "</td>";
txt += "<td width=10% align=center>" + Math.round(DelegatorReward*100)/100 + "</td>";
txt += "<td width=10% align=center>" + Math.round(Qfee*1000)/10 + " %" + "</td>";
txt += "<td width=30% align=left>" + status + "</td>";
txt += "</tr>";
}
txt += "</table>";
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("POST", "https://api6.tzscan.io/v3/delegator_rewards_with_details/" + KT1, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
/*Fonction to fetch the data for every cycle on the second API
// Data Recolted (Cycle, Payment)
// Try to merge with the first table according to the value of cycle
// // KT19www5fiQNAiqTWrugTVLm9FB3th5DzH54*/
function calculate3() {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { table: "cycle", limit: 10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
var KT1 = $('#KT1').val();
//console.log(KT1);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table><tr bgcolor=#000000 color=White>"
//txt += "<th>Block</th>"
txt += "<th>Cycle</th>"
txt += "<th>Paid</th>"
txt += "</tr>"
//If one transaction has been done for the cycle get from the API request 1 then I put the data on the last column of the table
for (var x = 0; x < 30; x++) {
if (KT1 == myObj[x].type.operations[0].destination.tz) {
console.log("Get one");
Block = myObj[x].type.operations[0].op_level;
console.log(Block);
PaiementCycle = Math.round(Block/4096);
PaiementCycle = PaiementCycle - 6;
console.log(PaiementCycle);
Paid = myObj[x].type.operations[0].amount/1000000;
console.log(Paid);
txt += "<tr>";
//txt += "<td width=10% align=center>" + Block + "</td>";
txt += "<td width=10% align=center>" + PaiementCycle + "</td>";
txt += "<td width=25% align=center>" + Paid + "</td>";
txt += "</tr>";
console.log(txt);
} else {
//console.log("Next");
}
}
txt += "</table>";
document.getElementById("demo2").innerHTML = txt;
return txt;
console.log("ici :" + xmlhttp);
}
};
xmlhttp.open("POST", "https://api6.tzscan.io/v3/operations/tz1XynULiFpVVguYbYeopHTkLZFzapvhZQxs?type=Transaction&number=100", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
$(function () {
/*when #tezos input loses focus, as per original question*/
$('#KT1').blur(function () {
calculate3();
calculate2();
console.log(back)
});
$('#KT1').change(function () {
calculate3();
calculate2();
});
$('#KT1').on(function () {
calculate3();
calculate2();
});
$('#KT1').keyup(function () {
calculate3();
calculate2();
});
$('#KT1').keydown(function () {
calculate3();
calculate2();
});
});
</script>
not tested - but i think it might help - i also tried to reduce function sizes for readability ;)
function getAndLogKT1(){
var KT1 = document.querySelector('#KT1')
console.log(KT1 && KT1.textContent)
return KT1 && KT1.textContent
}
function firstApiReadystatechange(){
}
function createTable(){
return document.createElement('table');
}
function addTableHeader(table, keys){
var thead = document.createElement('thead');
var tr = document.createElement('tr');
for(var i = 0; i < keys.length; i++){
var th = document.createElement('th')
var text = document.createTextNode(keys[i])
th.appendChild(text)
tr.appendChild(th)
}
thead.appendChild(tr)
table.appendChild(thead)
}
function addRowToTableBody(table, rowItems){
var body = table.querySelector('tbody')
if(!body){
body = document.createElement('tbody')
table.appendChild(body)
}
var tr = document.createElement('tr')
for(var i = 0; i < rowItems.length; i++){
var td = document.createElement('td')
var text = document.createTextNode(rowItems[i])
td.appendChild(text)
tr.appendChild(td)
}
body.appendChild(tr)
}
function getDbParam(dbParmaObj){
return JSON.stringify(dbParmaObj)
}
function sendRequestFirstApi(xmlhttp, KT1, dbParam){
xmlhttp.open("POST", "https://api6.tzscan.io/v3/delegator_rewards_with_details/" + KT1, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
function fetchDataForEveryCycleOnFirstApi(){
return new Promise((resolve, reject) => {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
var Qfee = 0.08;
if(this.readyState === 4 && this.status === 200){
try {
var responseObj = JSON.parse(this.responseText)
resolve(responseObj)
} catch {
reject({err: "json parse error"})
}
}
}
sendRequestFirstApi(xmlhttp, getAndLogKT1(), getDbParam({table: "cycle", limit: 10}))
})
}
function sendRequestSecondApi(xmlhttp, dbParam){
xmlhttp.open("POST", "https://api6.tzscan.io/v3/operations/tz1XynULiFpVVguYbYeopHTkLZFzapvhZQxs?type=Transaction&number=100", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
function fetchDataForEveryCycleOnSecondApi(){
return new Promise((resolve, reject) => {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
var Qfee = 0.08;
if(this.readyState === 4 && this.status === 200){
try {
var responseObj = JSON.parse(this.responseText)
resolve(responseObj)
} catch {
reject({err: "json parse error"})
}
}
}
sendRequestSecondApi(xmlhttp, getDbParam({table: "cycle", limit: 10}))
})
}
function parseObjectCycleHashed(respObject){
var retObj = {}
for(var x in respObject){
retObj[respObject[x]['cycle']] = respObject[x]
}
return retObj
}
function mergeCycleHashedResponseObjects(a,b){
let cyclesA = Object.keys(a)
var retObj = Object.assign({}, b)
for(var i = 0; i < cyclesA.length; i++){
Object.assign(retObj, {[cyclesA[i]]: a[cyclesA[i]] })
}
return retObj
}
function addToDOM(element, querySelector){
var el = document.querySelector(querySelector)
el && el.appendChild(element)
}
async function main(){
var responseObjApiOne = await fetchDataForEveryCycleOnFirstApi();
var responseObjApiTwo = await fetchDataForEveryCycleOnSecondApi();
var responseObjApiOneCycleBased = parseObjectCycleHashed(responseObjApiOne);
var responseObjApiTowCycleBased = parseObjectCycleHashed(responseObjApiTwo);
var mergedObject = mergeCycleHashedResponseObjects(responseObjApiOneCycleBased, responseObjApiTowCycleBased)
var table = createTable()
const headerKeys = [
"Cycle",
"Balance",
"Share",
"Reward",
"Fee",
"Status",
"Paid"
]
addTableHeader(table, headerKeys)
for(var cycle in mergedObject){
addRowToTableBody(table, headerKeys.map(columnTitle => {
return mergedObject[cycle][columnTitle]
}))
}
addToDOM(table, "dmeo2")
}

Multiple JSON files in one request from Javascript

I have two different codes for two different URL to fetch data. Code is as below :
Code 1 :
<script language="javascript" type="text/javascript">
var xmlHttp;
function parseBoolean(value) {
return (typeof value === "undefined") ? false : value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
function call_post(){
createXMLHttpRequest();
var vosRequest = new Object();
vosRequest.accounts = new Array(1);
vosRequest.accounts[0] = new Object();
vosRequest.accounts[0] = document.getElementById("accounts").value;
xmlHttp.open("POST", "http://..../GetCustomer", true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xmlHttp.onreadystatechange = showResult;
xmlHttp.send(JSON.stringify(vosRequest));
document.getElementById("postText").innerHTML = "<br>Request Format: " + JSON.stringify(vosRequest) + "</br>";
document.getElementById("responseText").innerHTML = "";
}
function showResult(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
document.getElementById("responseText").innerHTML = "<br>Response Format: " + xmlHttp.responseText + "</br>";
document.body.scrollTop=document.body.scrollHeight;
var json = JSON.parse(xmlHttp.responseText);
document.getElementById('id01').innerHTML = json.infoCustomers[0].infoCustomerAdditional.linkMan;
document.getElementById('id02').innerHTML = json.infoCustomers[0].account;
document.getElementById('id03').innerHTML = json.infoCustomers[0].name;
var num = json.infoCustomers[0].money;
var n = num.toFixed(3);
document.getElementById('id04').innerHTML = n;
var d = new Date(json.infoCustomers[0].validTime);
d = d.toGMTString();
document.getElementById('id05').innerHTML = d;
}
}
}
</script>
Code 2:
<script language="javascript" type="text/javascript">
var xmlHttp;
function parseBoolean(value) {
return (typeof value === "undefined") ? false : value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
function call_post(){
createXMLHttpRequest();
var vosRequest = new Object();
if(document.getElementById("checkbox_account").checked){
vosRequest.account = document.getElementById("account").value;
}
if(document.getElementById("checkbox_areaCode").checked){
vosRequest.areaCode = document.getElementById("areaCode").value;
}
if(document.getElementById("checkbox_period").checked){
vosRequest.period = parseFloat(document.getElementById("period").value);
}
if(document.getElementById("checkbox_beginTime").checked){
vosRequest.beginTime = document.getElementById("beginTime").value;
}
if(document.getElementById("checkbox_endTime").checked){
vosRequest.endTime = document.getElementById("endTime").value;
}
xmlHttp.open("POST", "http://.../GetReportCustomerLocationFee", true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xmlHttp.onreadystatechange = showResult;
xmlHttp.send(JSON.stringify(vosRequest));
document.getElementById("postText").innerHTML = "<br>Request Format: " + JSON.stringify(vosRequest) + "</br>";
document.getElementById("responseText").innerHTML = "";
}
function showResult(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
document.getElementById("responseText").innerHTML = "<br>Response Format: " + xmlHttp.responseText + "</br>";
document.body.scrollTop=document.body.scrollHeight;
var obj, dbParam, xmlhttp, myObj, x, txt = "";
var json = JSON.parse(xmlHttp.responseText);
//txt += ""
for (x=0;x<json.infoReportCustomerLocationFees.length;x++) {
txt += "<tr><td>" + json.infoReportCustomerLocationFees[x].areaCode + "</td>";
txt += "<td>" + json.infoReportCustomerLocationFees[x].areaName + "</td>";
json.infoReportCustomerLocationFees[x].totalFee = json.infoReportCustomerLocationFees[x].totalFee.toFixed(3);
txt += "<td>" + json.infoReportCustomerLocationFees[x].totalFee + "</td>";
txt += "<td>" + json.infoReportCustomerLocationFees[x].totalTime + "</td>";
txt += "<td>" + json.infoReportCustomerLocationFees[x].totalSuiteFee + "</td>";
txt += "<td>" + json.infoReportCustomerLocationFees[x].totalSuiteFeeTime + "</tr></td>";
}
// txt += "</table>"
document.getElementById("demo1").innerHTML = txt;
}
}
}
function load(){
document.getElementById("account").value = "ABC";
document.getElementById("areaCode").value = "1";
document.getElementById("period").value = "7";
document.getElementById("beginTime").value = "20170828";
document.getElementById("endTime").value = "20170903";
}
</script>
Both the codes are in two different html files and as an individual, both runs fine and fetches data.
I want to fetch the data of both the url in one html, i.e. I want to merge both the files and retreive data of both the request in single HTML file.
Can u suggest how can i do it? I have searched on stackoverflow but not able to find the right solution.
Thanks in advance.

onchange didn't work inside my function that render json parse

I have this code from w3school and modified it to suit my need and I come up with this code
<div id="city"></div>
<p id="demo"></p>
<div id="province"></div>
<script>
(function () {
var xmlhttp = new XMLHttpRequest();
var url = "http://getpark.net/city/read";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<div class='row'>" +
"<div class='large-12 columns'>" +
"<label>City</label>" +
"<select id='select' name='city' onchange='change()'>";
for(i = 0; i < arr.length; i++) {
out += "<option value='" +
arr[i].cityId +
"'>" +
arr[i].cityName +
"</option>";
}
out += "</select>" +
"</div>" +
"</div>";
document.getElementById("city").innerHTML = out;
}
function change() {
var x = document.getElementById("select").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
})();
but why that onchange in change() function didn't work out? I see it from w3school.
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onchange
thank you.
Your change-function should be in the global scope. You only have to move the declaration of the function directly after the script-tag.
<script>
function change() {
var x = document.getElementById("select").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
(function () {
[..]

How to make xmlhttprequest periodically?

I want to loop an httprequest every 5 seconds.
Here is my code :
var xmlhttp2 = new XMLHttpRequest();
var url2 = "http:...";
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
var response2 = xmlhttp2.responseText;
var response2 = xmlhttp2.responseText;
var json2 = JSON.parse(response2);
for (var i = 2; i < json2.length; i++){
document.getElementById('table2').innerHTML += '<tr><td>' + json2[i].nm + '</td><td>' + json2[i].id + '</td><td id="uid_'+i+'">' + json2[i].stn + '</td></tr>';
}
}
xmlhttp2.open("GET", url2, true);
xmlhttp2.send();
I tried to put this whole code in a function and called
setInterval(myFunction,5000);
This works. However the table is displaying several times.
I tried
setInterval("xmlhttp2.send();",5000);
and this doesn't work. The request is made only once.
Any advice ?
Thank you
You can clear the table before populating it with the server response
Answer
var xmlhttp2 = new XMLHttpRequest();
var url2 = "http:...";
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
var response2 = xmlhttp2.responseText;
var response2 = xmlhttp2.responseText;
var json2 = JSON.parse(response2);
var table = document.getElementById('table2');
table.innerHTML = '';
for (var i = 2; i < json2.length; i++){
table.innerHTML += '<tr><td>' + json2[i].nm + '</td><td>' + json2[i].id + '</td><td id="uid_'+i+'">' + json2[i].stn + '</td></tr>';
}
}
xmlhttp2.open("GET", url2, true);
xmlhttp2.send();
Use setInterval(myFunction,5000); to make periodic request.
Edited
var xmlhttp2 = new XMLHttpRequest();
var url2 = "http:...";
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
var response2 = xmlhttp2.responseText;
var response2 = xmlhttp2.responseText;
var json2 = JSON.parse(response2);
var tableBody = document.getElementById('table2Body');
tableBody.innerHTML = '';
for (var i = 2; i < json2.length; i++){
tableBody.innerHTML += '<tr><td>' + json2[i].nm + '</td><td>' + json2[i].id + '</td><td id="uid_'+i+'">' + json2[i].stn + '</td></tr>';
}
}
xmlhttp2.open("GET", url2, true);
xmlhttp2.send();

Categories

Resources