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();
Related
So I have some Javascript that does an XMLHttpRequest (xhr), on receival of response it does a second response (xhr2) to get remaining data.
But I have now split this second call into batches so that it has to call multiple times depending on how much data there. After the first request I know how many calls I haven to make
var batches = Math.ceil((counter.innerText.substring(0,counter.innerText.indexOf(" ")) - 100) / 1000);
But then I am just making multiple calls to xdr2, but this doesn't work because it closes after first call. So I realize I probably need to initialize multiple XMLHttpRequest based on the value of batches, but how do I define the onreadystatechange function succinctly.
function get_tracklist_data(path, cid, title)
{
var xhr = new XMLHttpRequest();
var xhr2 = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var counter = document.getElementById("counter");
counter.innerHTML = xhr.responseText.substring(0, xhr.responseText.indexOf(":"));
var data = document.getElementById("data");
data.innerHTML = xhr.responseText.substring(xhr.responseText.indexOf(":") + 1);
//Work out how many calls we need to make
var batches = Math.ceil((counter.innerText.substring(0,counter.innerText.indexOf(" ")) - 100) / 1000);
for(i=1; i<batches;i++)
{
xhr2.open('GET',path + '?cid=' + cid + "&title=" + title+"&batch=" + i, true);
xhr2.send();
}
}
};
xhr2.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var data = document.getElementById("tbody");
data.innerHTML+=xhr2.responseText;
}
};
xhr.open('GET',path + '?cid=' + cid + "&title=" + title +"&batch=0", true);
xhr.send();
};
Update to make xhr2 local variable in loop, but doesnt seem to work properly Im getting the same data back multiple times.
function get_tracklist_data(path, cid, title)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var counter = document.getElementById("counter");
counter.innerHTML = xhr.responseText.substring(0, xhr.responseText.indexOf(":"));
var data = document.getElementById("data");
data.innerHTML = xhr.responseText.substring(xhr.responseText.indexOf(":") + 1);
//Work out how many calls we need to make
var batches = Math.ceil((counter.innerText.substring(0,counter.innerText.indexOf(" ")) - 100) / 1000);
for(i=1; i<batches;i++)
{
var xhr2 = new XMLHttpRequest();
xhr2.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var data = document.getElementById("tbody");
data.innerHTML+=xhr2.responseText;
}
};
xhr2.open('GET',path + '?cid=' + cid + "&title=" + title+"&batch=" + i, true);
xhr2.send();
}
}
};
xhr.open('GET',path + '?cid=' + cid + "&title=" + title +"&batch=0", true);
xhr.send();
};
here example using await fetch() and fetch().then()
function listenForButtonCollapse(buttonId, collapseId, buttonText) {
let button = document.getElementById(buttonId);
let section = document.getElementById(collapseId);
if (section != null) {
section.addEventListener('show.bs.collapse', function() {
button.innerText = 'Hide ' + buttonText;
});
section.addEventListener('hide.bs.collapse', function() {
button.innerText = 'Show ' + buttonText;
});
}
}
async function get_tracklist_data(path, cid, title) {
let xhr = await fetch(path + '?cid=' + cid + "&title=" + title + "&batch=0");
let responseText = await xhr.text()
let counter = document.getElementById("counter");
counter.innerHTML = responseText.substring(0, responseText.indexOf(":"));
let data = document.getElementById("data");
data.innerHTML = responseText.substring(responseText.indexOf(":") + 1);
listenForButtonCollapse('show_focus_button', 'focus_id', 'Spotlight');
listenForButtonCollapse('show_albums_button', 'albums_id', 'Albums');
listenForButtonCollapse('show_tracks_button', 'tracks_id', 'Tracks');
listenForButtonCollapse('show_works_button', 'works_id', 'Works');
//Work out how many calls we need to make
let batches = Math.ceil((counter.innerText.substring(0, counter.innerText.indexOf(" ")) - 100) / 1000);
data = document.getElementById("tbody");
for (i = 1; i < batches; i++) {
fetch(path + '?cid=' + cid + "&title=" + title + "&batch=" + i)
.then(resp => resp.text())
.then(responseText => {
data.innerHTML += responseText;
})
}
}
Using XMLHttpRequest: save xhr object into array then add parameter to the callback listXHR[i].onreadystatechange = function(x) then call x.target for current xhr object
function get_tracklist_data(path, cid, title) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var counter = document.getElementById("counter");
counter.innerHTML = xhr.responseText.substring(0, xhr.responseText.indexOf(":"));
var data = document.getElementById("data");
data.innerHTML = xhr.responseText.substring(xhr.responseText.indexOf(":") + 1);
//Work out how many calls we need to make
var batches = Math.ceil((counter.innerText.substring(0, counter.innerText.indexOf(" ")) - 100) / 1000);
var listXHR = []
for (i = 1; i < batches; i++) {
listXHR[i] = new XMLHttpRequest();
listXHR[i].onreadystatechange = function(x) {
if (x.target.readyState == 4 && x.target.status == 200) {
var data = document.getElementById("tbody");
data.innerHTML += x.target.responseText;
}
};
listXHR[i].open('GET', path + '?cid=' + cid + "&title=" + title + "&batch=" + i, true);
listXHR[i].send();
}
}
};
xhr.open('GET', path + '?cid=' + cid + "&title=" + title + "&batch=0", true);
xhr.send();
};
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")
}
This is my code:
let info = document.getElementById('info');
let week = document.getElementById('week');
/*Initializer Function*/
window.addEventListener('load', () => {
let long;
let lat;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
long = position.coords.longitude;
lat = position.coords.latitude;
const proxy = 'https://cors-anywhere.herokuapp.com/';
const api = `${proxy}https://api.darksky.net/forecast/d571a1e2483b31605b94edaae84c647e/${lat},${long}`;
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
let obj = JSON.parse(this.responseText);
console.log(obj);
document.getElementById('temperature-degree').innerHTML = obj.currently.apparentTemperature;
document.getElementById('location').innerHTML = obj.timezone;
document.getElementById('temperature-description').innerHTML = obj.currently.summary;
setIcons(obj.currently.icon, document.getElementById('currentDayIcon'));
for (let i = 0; i < obj.hourly.data.length; i++) {
info.innerHTML += `<div id='hour${i + 1}' class='hourly'>` + `<canvas id='hourIcon${i + 1}'></canvas>` + `<h3 id='hourTemp${i + 1}'></h3>` + `<p id='hourSummary${i + 1}'></p>` + '</div>';
setIcons(obj.hourly.data[i].icon, document.getElementById(`hourIcon${i + 1}`));
document.getElementById(`hourTemp${i + 1}`).innerHTML = obj.hourly.data[i].temperature;
document.getElementById(`hourSummary${i + 1}`).innerHTML = obj.hourly.data[i].summary;
}
for (let i = 0; i < 5; i++) {
week.innerHTML += `<div id='day${i + 1}' class='daily'>` + `<canvas id='dayIcon${i + 1}'></canvas>` + `<h2 id='dayTemp${i + 1}'></h2>` + `<p id='daySummary${i + 1}'></p>` + '</div>';
setIcons(obj.daily.data[i].icon, document.getElementById(`dayIcon${i + 1}`));
document.getElementById(`dayTemp${i + 1}`).innerHTML = obj.daily.data[i].temperatureMax;
document.getElementById(`daySummary${i + 1}`).innerHTML = obj.daily.data[i].summary;
}
}
};
xhr.open("GET", api, true);
xhr.send();
});
}
function setIcons(icon, iconId) {
const skycons = new Skycons({color: 'white'});
const currentIcon = icon.replace(/-/g, '_').toUpperCase();
skycons.play();
return skycons.set(iconId, Skycons[currentIcon]);
}
;
});
...and the problem is that when it comes to the icons being loaded and displayed it's only the last one that actually displays. I don't know what the problem is because if it's successful for the last one, then it should be successful for the previous 47 since the last is the same iteration done for the 48th time. Any ideas?
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.
I tried to run this but it doesn't work.
It is intended to return a variable assigned inside a function, that was passed as callback to sendRequest(), which is retrieving data from the Internet through XMLHttpRequest asynchronously.
Can anyone tell me why this is not working and always returning ""?
function sendRequest(requestCode, args, callback){
var req = requestEngineUrl + "?req=" + requestCode + ";" + args;
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4)
{
if(callback != null){
callback(xmlHttp.responseText);
}
}
};
xmlHttp.open("GET", req, true);
xmlHttp.send(null);
}
this.assembleProcess = function(){
if(!isNull(this.id) && !isNull(this.titles)){
var titles = this.titles;
var id = this.id;
c = "";
sendRequest('304', id,
function(result){
var res = result.split("/");
var title = res[0];
var possibilities = res[1];
var fcontent = title + '<br><div>';
if(titles.length != possibilities){
console.log("WARNING: [SURVEYCARD].titles has not the same length as possibilities");
}
for(i = 0; i < possibilities; i++){
fcontent += '<div><a onclick="sendRequest("301",' + id + ',' + i + ',null)">' + titles[i] + '</a></div>';
}
fcontent += '</div>';
c = fcontent;
});
return c;
}
As an XMLHttpRequest is async, you should write an async function for that matter, like this
this.assembleProcess = function(callback){
if(!isNull(this.id) && !isNull(this.titles)){
var titles = this.titles;
var id = this.id;
c = "";
sendRequest('304', id,
function(result){
var res = result.split("/");
var title = res[0];
var possibilities = res[1];
var fcontent = title + '<br><div>';
if(titles.length != possibilities){
console.log("WARNING: [SURVEYCARD].titles has not the same length as possibilities");
}
for(i = 0; i < possibilities; i++){
fcontent += '<div><a onclick="sendRequest("301",' + id + ',' + i + ',null)">' + titles[i] + '</a></div>';
}
fcontent += '</div>';
c = fcontent;
callback(c)
});
}
and then, instead of using this.assembleProcess as a function with a result, you should pass a function as parameter:
Instead of
console.log(this.assembleProcess);
do this
this.assembleProcess(function(c){console.log(c)});