How to proper target JSON response when using append - javascript

I cannot seem to get the syntax right when targeting JSON response.
In my project I have a <div id="percentage"></div>.
I want to append the score as text to the div but i'm getting "Cannot read property 'categories' of undefined" error in the console.
I think it is a syntax error from my side.
How to fix it?
JSON:
{"lighthouseResult":{"categories":{"performance":{"score":1.0},"accessibility":{"score":0.9},"best-practices":{"score":0.92},"seo":{"score":0.8},"pwa":{"score":0.54}}}}
Javascript:
function loadAnalysis() {
var xhttp = new XMLHttpRequest();
var url = document.getElementById("url").value;
if (url == "") {
alert("Please enter URL");
return;
}
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
var table = document.createElement('table');
table.setAttribute('class', 'result');
var properties = ['performance', 'accessibility', 'best-practices', 'seo', 'pwa'];
var capitalize = function(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
var tr = document.createElement('tr');
for (var i = 0; i < properties.length; i++) {
var th = document.createElement('th');
th.classList.add("category");
th.appendChild(document.createTextNode(capitalize(properties[i])));
tr.appendChild(th);
}
table.appendChild(tr);
var tr, row;
console.log("jsonResponse", jsonResponse);
var categories = Object.keys(jsonResponse["lighthouseResult"]);
for (var r = 0; r < categories.length; r++) {
tr = document.createElement('tr');
row = jsonResponse["lighthouseResult"][categories[r]];
var ids = 'performance,accessibility,best-practices,seo,pwa'.split(',');
for (var i = 0; i < properties.length; i++) {
    var td = document.createElement('td');
    td.id = ids[i];
td.className = "score";
td.appendChild(document.createTextNode(row[properties[i]].score));
var seldiv = document.getElementById("percentage");
seldiv.append(data.lighthouseResult.categories.performance.score);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('analysisTable').appendChild(table);
}
};
xhttp.open("GET", "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + encodeURIComponent(url) +
"&fields=lighthouseResult%2Fcategories%2F*%2Fscore&prettyPrint=false&strategy=desktop&category=performance&category=pwa&category=best-practices&category=accessibility&category=seo&key=AIzaSyDSNxhf0capOwppqlg9wZJUvzBewxf6mHU", true);
xhttp.send();
}
Part where I'm struggling with:
var seldiv = document.getElementById("percentage");
seldiv.append(data.lighthouseResult.categories.performance.score);

I think you are after jsonResponse.lighthouseResult.categories.performance.score. You perform var jsonResponse = JSON.parse(data); so data is essentially text, and the JSON representation of that text is jsonResponse

Related

Can we able to update a particular cell in csv file using Javascript?

Can we able to update a particular cell in csv file using Javascript?
Can anyone share please share the sample javascript code?
Considering you have a workbook, here is how you may loop through the rows and change the cell value:
var rows = workbook.sheets[0].rows;
for (var ri = 0; ri < rows.length; ri++) {
var row = rows[ri];
for (var ci = 0; ci < row.cells.length; ci++) {
var cell = row.cells[ci];
cell.value = new_data;
cell.hAlign = "left";
}
}
Update
var file = document.getElementById('docpicker')
file.addEventListener('change', importFile);
function importFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = e => {
var contents = processExcel(e.target.result);
console.log(contents)
}
r.readAsBinaryString(f);
} else {
console.log("Failed to load file");
}
}
function processExcel(data) {
var workbook = XLSX.read(data, {
type: 'binary'
});
// inject your logic as per need
var rows = workbook.sheets[0].rows;
for (var ri = 0; ri < rows.length; ri++) {
var row = rows[ri];
for (var ci = 0; ci < row.cells.length; ci++) {
var cell = row.cells[ci];
cell.value = new_data;
cell.hAlign = "left";
}
}
};

How to fix duplication of dynamic input creation at press of hotkey

I have a legacy barcode scanning application, which is used to issue items from the store. It has a combo box which has a list of all pending orders and when the user selects an order, it will list out the items expected to be issued with their quantities. Then the user presses 'f7' as a shortcut key and a new barcode field is added dynamically and then they have to scan the barcode of the bin location and after it is validated, automatically another field for the item code is added dynamically. After the item code is validated, the quantity field is added dynamically wherein the user inputs the quantity taken from that bin location. The user presses 'f7' again and the process repeats unless they finish collecting the items.
At last, they save the order and proceeds with another order.
The problem which I am facing right now is that the number of times user selects the order and presses 'f7', that number of fields are added automatically.
Example, the first time when the page loads, the user selects the order, presses 'f7', one field for bin location is added automatically, no issue here. Now, due to some reason, the user selects a second order and presses 'f7', now 2 bin location fields are added automatically. The user selects third order and presses 'f7', now 3 bin location fields are added automatically. This goes on repeating unless the user refreshes the page and starts new.
There is a variable serial defined which I have tried resetting at the time of user selecting the order but the problem still exists. I have tried resetting the variable at different places, but the problem doesn't go away.
I have used hotkeys javascript to use 'f7' as the shortcut
https://unpkg.com/hotkeys-js#3.7.1/dist/hotkeys.js
During the HTML load, a select input box is populated with all the pending orders and the below code calls the function ValueChanged with the order number when the value is changed:
<select name="Request" onchange="ValueChanged(this);;">
The function ValueChanged builds a URL with the order number and passes an Ajax request to another page through function SendAjaxRequest which collects the required data and then another function SetValues builds a table with the data on the page. Now, this function SetValues has the shortcut function hotkeys which adds the field dynamically.
Below is the javascript code
stopEvent = function(ffevent)
{
var current_window = window;
if(current_window.event) //window.event is IE, ffevent is FF
{
//IE
current_window.event.cancelBubble = true; //this stops event propagation
current_window.event.returnValue = false; //this prevents default (usually is what we want)
}
else
{
//Firefox
ffevent.stopPropagation();
ffevent.preventDefault();
};
}
function validateAllInputBoxes(ffevent)
{
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; ++i)
if(inputs[i].type === 'text')
if(inputs[i].value === '')
{
alert("form could not be sent one input text field is empty");
stopEvent(ffevent);
}
var x = document.forms["myForm"]["Request"].value;
if (x == null || x == "") {
alert("Select GRN");
stopEvent(ffevent);
}
var inputFormDiv = document.getElementsByTagName('input').length;
if (inputFormDiv<=1) {
alert("Enter atleast one BIN Information");
stopEvent(ffevent);
}
}
function addRow() {
var myName = document.getElementById("name");
var age = document.getElementById("age");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= myName.value;
row.insertCell(2).innerHTML= age.value;
}
var deleteRow = function (link) {
var row = link.parentNode.parentNode;
var table = row.parentNode;
table.parentNode.removeChild(table);
}
//function deleteRow(obj) {
// var index = obj.parentNode.parentNode.rowIndex;
// var table = document.getElementById("myDynamicTable2");
// table.deleteRow(index);
//}
function addTable() {
}
function load() {
console.log("Page load finished");
}
function GetXmlHTTP() {
//first check for IE:
if (window.ActiveXObject) {
var objXML = 0;
try {
objXML = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(ex) {
try {
objXML = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(ex) {
alert("AJAX: your browser does not support proper XMLHTTP");
}
}
return objXML;
}
//maybe Mozilla?
if (window.XMLHttpRequest)
return new XMLHttpRequest();
//unknown browser..
alert("AJAX: unknown browser.");
return 0;
} //end function GetXmlHTTP
/*
this function send request to the given URL via
GET method.
*/
function SendAjaxRequest(strURL) {
//get xmlhttp component:
var objXML = GetXmlHTTP();
//got anything?
if (!objXML)
return false;
//attach local callback function:
objXML.onreadystatechange = function()
{
//ready?
if (objXML.readyState == 4)
{
//get status:
var status=objXML.status;
//maybe not successful?
if (status != 200)
{
// alert("AJAX: server status " + status);
}
else
{
//get response text:
var strResponse = objXML.responseText;
document.getElementById("myDynamicTable").innerHTML = "";
document.getElementById("myDynamicTable1").innerHTML = "";
document.getElementById("myDynamicTable2").innerHTML = "";
document.getElementById("myDynamicTable3").innerHTML = "";
SetValues(strResponse);
}
}
}
//send request:
objXML.open("GET", strURL, true);
objXML.send(null);
} //end function SendAjaxRequest
function SendAjaxRequest1(strURL) {
//get xmlhttp component:
var objXML = GetXmlHTTP();
//got anything?
if (!objXML)
return false;
//attach local callback function:
objXML.onreadystatechange = function()
{
//ready?
if (objXML.readyState == 4)
{
//get status:
var status=objXML.status;
//maybe not successful?
if (status != 200)
{
// alert("AJAX: server status " + status);
}
else
{
//get response text:
var strResponse = objXML.responseText;
SetValues1(strResponse);
}
}
}
//send request:
objXML.open("GET", strURL, true);
objXML.send(null);
} //end function SendAjaxRequest
function SendAjaxRequest2(strURL) {
//get xmlhttp component:
var objXML = GetXmlHTTP();
//got anything?
if (!objXML)
return false;
//attach local callback function:
objXML.onreadystatechange = function()
{
//ready?
if (objXML.readyState == 4)
{
//get status:
var status=objXML.status;
//maybe not successful?
if (status != 200)
{
// alert("AJAX: server status " + status);
}
else
{
//get response text:
var strResponse = objXML.responseText;
SetValues2(strResponse);
}
}
}
//send request:
objXML.open("GET", strURL, true);
objXML.send(null);
} //end function SendAjaxRequest
function ValueChanged(oDDL)
{
var selectedValue = oDDL.value;
if (selectedValue.length > 0)
{
var strURL = "RetrieveBIN.asp?value=" + selectedValue + "&ts=" + (new Date()).getTime();
//SetValues("Loading...|Loading...|Loading...");
rqstnumber = selectedValue;
SendAjaxRequest(strURL);
}
}
function ValueChangedDesc(oDDL)
{
var selectedValue = oDDL.value;
selectedValueBIN = oDDL.value;
if (selectedValue.length > 0)
{
var strURL = "RetrieveDesc.asp?value=" + selectedValue + "&ts=" + (new Date()).getTime();
//SetValues("Loading...|Loading...|Loading...");
SendAjaxRequest1(strURL);
}
}
function ValueChangedItem(oDDL)
{
var xperia = document.forms["myForm"]["Request"].value;
//var binival = bini.value;
var selectedValue = oDDL.value;
if (selectedValue.length > 0)
{
var strURL = "RetrieveItem.asp?value=" + selectedValue + "&ts=" + (new Date()).getTime() + "&rqn=" + xperia + "&bin=" + selectedValueBIN;
//alert(strURL);
//SetValues("Loading...|Loading...|Loading...");
SendAjaxRequest2(strURL);
}
}
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(3);
}
function SetValues1(sRawData)
{
var arrData = sRawData.split("|");
var oForm = document.forms["GetData"];
var txt = document.activeElement.name;
var numb = txt.match(/\d/g);
numb = numb.join("");
var elem = document.getElementById('1ItemDesc');
//elem.value = arrData[0];
var str = arrData[0];
var n = str.length;
if (n>0) {
//
//var myTableDiv2 = document.getElementById("myDynamicTable2");
//var table1 = document.createElement('TABLE');
//table1.border='1';
//var tableBody2 = document.createElement('TBODY');
//table1.appendChild(tableBody2);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
var input = document.createElement('input');
input.type = "text";
input.setAttribute("size",'15');
input.setAttribute("autofocus",'True');
input.setAttribute("value", '');
input.setAttribute("name", serial+'ItemCode');
input.setAttribute("id", serial+'ItemCode');
//input.setAttribute("autofocus",'True');
input.setAttribute("required",'true');
input.setAttribute("data-parsley-required",'true');
input.onkeydown = function(){ValueChangedItem(this);};
var lblt = document.createTextNode('Item Code - ');
var td = document.createElement('TD');
td.appendChild(lblt);
td.appendChild(input);
tr.appendChild(td);
//alert(arrData[0]);
myTableDiv2.appendChild(table1);
//document.getElementById(serial+"ItemCode").focus();
//document.getElementById(serial+"ItemCode").focus();
//document.getElementById(serial+"ItemCode").focus();
var inputs1 = document.getElementById(serial+'ItemCode');
inputs1.focus();
inputs1.focus();
//inputs1.focus();
//for (var i = 0; i < inputs.length; i++) {
// if (inputs[i].name = serial+'ItemCode') {
// alert(inputs[1].name);
//alert('arif');
//inputs[i].focus();
//break;
// }
//
//}
serial++;
} else {
}
}
function SetValues2(sRawData)
{
var arrData = sRawData.split("|");
var oForm = document.forms["GetData"];
//var txt = document.activeElement.name;
//var numb = txt.match(/\d/g);
//numb = numb.join("");
//var elem = document.getElementById('1ItemDesc');
//elem.value = arrData[0];
var str = arrData[0];
var n = str.length;
if (n>0) {
//
//var myTableDiv2 = document.getElementById("myDynamicTable2");
//var table3 = document.createElement('TABLE');
//table3.border='1';
//var tableBody3 = document.createElement('TBODY');
//table3.appendChild(tableBody3);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
var lblt = document.createTextNode('Item Desc - '+arrData[0]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "100px";
var input = document.createElement('input');
input.type = "text";
input.setAttribute("size",'15');
input.setAttribute("value", '');
input.setAttribute("name", serial+'Qty');
input.setAttribute("id", serial+'Qty');
input.setAttribute("required",'true');
input.setAttribute("data-parsley-required",'true');
input.setAttribute("data-parsley-type",'number');
input.onchange = setTwoNumberDecimal;
td.appendChild(lblt);
tr.appendChild(td);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
var td = document.createElement('TD');
var lblt1 = document.createTextNode('Enter Quantity - ');
td.appendChild(lblt1);
td.appendChild(input);
tr.appendChild(td);
//alert(arrData[0]);
myTableDiv2.appendChild(table1);
//var inputs = document.getElementsByName(serial+'Qty');
//for (var i = 0; i < inputs.length; i++) {
// if (inputs[i].name = serial+'Qty') {
// alert(inputs[1].name);
//inputs[i].focus();
//break;
// }
//
//}
var inputs2 = document.getElementById(serial+'Qty');
inputs2.focus();
inputs2.focus();
//inputs2.focus();
serial++;
} else {
}
//var allTags = document.body.getElementsByTagName('*');
//var ids = [];
//for (var tg = 0; tg< allTags.length; tg++) {
// var tag = allTags[tg];
// if (tag.id) {
// ids.push(tag.id);
// }
//}
//alert(ids);
//var oformo = document.forms["1ItemCode");
//alert (oForm0);
//var valdesc = document.getElementById("");
}
function SetValues(sRawData)
{
//window.location.reload();
var arrData = sRawData.split("|");
var oForm = document.forms["GetData"];
//$('myDynamicTable2, table1').remove();
$('#myDynamicTable2').closest('tr').remove();
document.getElementById("myDynamicTable").innerHTML = "";
document.getElementById("myDynamicTable1").innerHTML = "";
document.getElementById("myDynamicTable2").innerHTML = "";
document.getElementById("myDynamicTable3").innerHTML = "";
//document.getElementById("myDynamicTable2").innerHTML = "<br>";
//document.getElementById("table1").innerHTML = "";
serial=1;
var myTableDiv = document.getElementById("myDynamicTable");
var p=1;
var u=0;
u=parseInt(arrData[0]);
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<u; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "80px";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "120px";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "50px";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "70px";
td.style.wordWrap = "break-word";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
var tr = document.createElement('TR');
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table);
var myTableDiv1 = document.getElementById("myDynamicTable1");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var j=0; j<1; j++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var btn = document.createElement('hyper');
var btnt = document.createTextNode('Press F7 to Add');
btn.appendChild(btnt);
btn.title = "Press F7 to Add";
btn.value = arrData[p];
var bin=1;
//----------shortcut.add("F7", function() {
hotkeys('f7', function(event, handler){
// Prevent the default refresh event under WINDOWS system
event.preventDefault()
// alert(serial+"BinLocation");
myTableDiv2 = document.getElementById("myDynamicTable2");
table1 = document.createElement('TABLE');
table1.border='1';
tableBody1 = document.createElement('TBODY');
table1.appendChild(tableBody1);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
for (var j=0; j<1; j++) {
var input = document.createElement('input');
input.type = "text";
input.setAttribute("size",'15');
input.setAttribute("autofocus",'True');
input.setAttribute("value", '');
input.setAttribute("name", serial+'BinLocation');
input.setAttribute("id", serial+'BinLocation');
input.setAttribute("required",'true');
input.setAttribute("data-parsley-required",'true');
//input.required = required;
input.onkeydown = function(){ValueChangedDesc(this);};
var btn = document.createElement('hyper');
var btnt = document.createTextNode('Delete');
btn.appendChild(btnt);
btn.title = "Delete";
//shortcut.add("f4", function() {deleteRow(this) });
btn.onclick = function() {deleteRow(this)};
var lblt = document.createTextNode('Bin Location - ');
var td = document.createElement('TD');
td.appendChild(lblt);
td.appendChild(input);
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(btn);
tr.appendChild(td);
bin++;
}
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
myTableDiv2.appendChild(table1);
var inputs = document.getElementById(serial+'BinLocation');
inputs.focus();
inputs.focus();
serial++;
});
var td = document.createElement('TD');
td.appendChild(btn);
tr.appendChild(td);
myTableDiv1.appendChild(table);
}
}
function validateForm() {
var x = document.forms["myForm"]["Request"].value;
var e = document.forms["myForm"];
e=e.getElementsByTagName('input');
e=(e.length)+1;
if (x == null || x == "") {
alert("Select GRN");
return false;
}
if (e==2) {
alert("2Number of fields is invalid");
return false;
}
//alert(e) ; // 6
if ((e - 2) % 3 !== 0) {
alert("Number of fields is invalid");
return false;
}
}
I expect that without refreshing, any number of times the user selects the order and presses 'f7', the bin location fields should not duplicate.
Thanks in advance.

How to populate array with results from a series of async requests

So I'm trying to get the names and scores that are in 2 arrays player_name and player_mmr. Calling both with player_name[i] and player_mmr[i] in the fillplayer function just returns undefined. I feel like I'm missing something obvious here but for the life of me can't figure it out. I'm guessing it has to do with the use of push.
var btnmatch = document.querySelector('#get-data');
var btnchat = document.querySelector('#get-chat');
var matchid = document.querySelector('#match-id');
var tableheaders = [
'Hero',
'level',
'Name',
'Kills',
'Deaths',
'assists',
'GPM',
'XPM',
'HD',
'TD'
];
var dataheaders = [
"hero_id",
'level',
'personaname',
'kills',
'deaths',
'assists',
'gold_per_min',
'xp_per_min',
'hero_damage',
'tower_damage'
];
var playerids = [
'player1',
'player2',
'player3',
'player4',
'player5',
'player6',
'player7',
'player8',
'player9',
'player10'
];
var playeraccounts = [];
var requests = [];
var playersdata = [];
var player_name = [];
var player_mmr = [];
btnmatch.addEventListener('click', function () {
GetMatchData(matchid.value);
});
btnchat.addEventListener('click', function () {
for (i in playeraccounts) {
requests[i] = new GetPlayerData(playeraccounts[i]);
}
console.log(player_name);
console.log(typeof player_name);
console.log(player_mmr);
fillplayer();
});
function GetPlayerData(accountid) {
var Url = 'https://api.opendota.com/api/players/' + accountid;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", Url, true);
xmlHttp.onreadystatechange = function ProcessRequestPlayer() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
if (xmlHttp.responseText == "Not found") {
console.log("not found");
} else {
var info = xmlHttp.responseText;
var playerjson = JSON.parse(info);
player_name.push(playerjson.profile.personaname);
if (playerjson.solo_competitive_rank === null) {
player_mmr.push(playerjson.mmr_estimate.estimate);
} else {
player_mmr.push(playerjson.solo_competitive_rank);
}
}
}
};
xmlHttp.send();
}
function GetMatchData(id) {
var Url = 'https://api.opendota.com/api/matches/' + id;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", Url, true);
xmlHttp.onreadystatechange = function ProcessRequestMatch() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
if (xmlHttp.responseText == "Not found") {
console.log("not found")
} else {
var info = xmlHttp.responseText;
var testjson = JSON.parse(info);
createTable2(testjson);
getaccountids(testjson);
}
}
};
xmlHttp.send();
}
function getaccountids(json) {
Object.keys(json.players).forEach(function (i) {
playeraccounts.push(json.players[i].account_id);
});
}
function fillplayer() {
console.log(player_name);
console.log(player_mmr);
for (var i = 0; i < playerids.length; i++) {
console.log(player_name[i]);
document.getElementById(playerids[i]).getElementsByClassName('name')[0].innerHTML = player_name + ': ';
document.getElementById(playerids[i]).getElementsByClassName('mmr')[0].innerHTML = player_mmr[i];
}
}
function createTable2(json) {
// Create table.
var table = "<table class='game-table'>";
table += "<thead>";
table += "<tr>";
for (var i = 0; i < 10; i++) {
table += "<th>" + tableheaders[i] + "</th>";
}
table += "</tr>";
table += "</thead>";
table += "<tbody>";
for (var i = 0; i < 5; i++) {
table += "<tr class='radiant'>";
for (var x = 0; x < dataheaders.length; x++) {
table += "<td>" + json.players[i][dataheaders[x]] + "</td>";
}
table += "</tr>";
}
for (var i = 5; i < 10; i++) {
table += "<tr class='dire'>";
for (var x = 0; x < dataheaders.length; x++) {
table += "<td>" + json.players[i][dataheaders[x]] + "</td>";
}
table += "</tr>";
}
table += "</tbody>";
table += "</table>";
var sectie = document.getElementById('table');
if (json.radiant_win == false) {
var winnertekst = document.createTextNode('Dire Victory');
} else {
var winnertekst = document.createTextNode('Radiant Victory');
}
console.log(table);
console.log(typeof table);
console.log(sectie);
document.getElementsByClassName('winnersect')[0].appendChild(winnertekst);
sectie.innerHTML = table;
}
As marekful said you could use promises or you could take a look to Async Functions
and if you're not targeting IE as a browser, you could use the
Fetch API
instead of XMLHttpRequest and have a cleaner structure. Both of these two return a promise that you can consume.
One more source that's showing how you can combine fetch and async functions
JavaScript Fetch API and using Async/Await .

create table from javascript variables

I've never been good with coding and what I did was mainly PHP not javascript. This is running on a Windows server that I have no ability to install anything new on.
I have a web page that someone else built that I am trying to reformat. The current one is an OpenLayers map.
I want to take the information on the map and put it on a table.
A PowerShell script outputs data to a txt file.
The web page imports that data does a few different things to it.
I end up with three columns of stuff I want to put on the table and there just shy of 20 rows.
This is what I've tried so far.
<table id="myTable">
<tr>
<td>Office</td>
<td>Server Ping</td>
<td>Circuit Ping</td>
</table>
function myCreateFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = fullname;
cell2.innerHTML = pingResultHTML;
cell3.innerHTML = circuitPrimaryResultHTML;
};
If needed I can post more or all of the page's code.
I'm operating under the assumption that if the variables can be used to populate info for popups on the map I should be able to just redirect them into a table.
Edit:
Here is additional info.
This is what calls the data from the txt file.
if (window.XMLHttpRequest)
{xmlhttp=new XMLHttpRequest();
}
else
{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
};
xmlhttp.open("GET","latest_results_list.txt",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseText;
var mySplitResult;
mySplitResult = xmlDoc.split("\r\n");
for(i = 0; i < mySplitResult.length; i++)
{
var locationStringCleaned = mySplitResult[i].replace(/(\r\n|\n|\r)/gm,"");
officeParameters = locationStringCleaned.split(",");
officelocation = officeParameters[0];
pingStatus = officeParameters[1];
pingTime = officeParameters[2];
primaryCircuit = officeParameters[3];
primaryCircuitTime = officeParameters[4];
addNewLocation(officelocation, pingStatus, pingTime, primaryCircuit, primaryCircuitTime);
This adds the site name.
if (officename == "SHO"){
fullname = "Stevens Point, WI";
} else if (officename == "RIC"){
fullname = "Richmond, VA";
} else if (officename == "DAV"){
fullname = "Davenport, IA";
} else if (officename == "GOL"){
fullname = "Goldsboro, NC";
} else if (officename == "IRV"){
fullname = "Irvine, CA";
} else if (officename == "MON"){
fullname = "Montgomery, AL";
} else if (officename == "MAD"){
fullname = "Madison, WI";
} else if (officename == "SAL"){
fullname = "Salem, OR";
} else if (officename == "SCO"){
fullname = "Scottsdale, AZ";
} else if (officename == "WES"){
fullname = "Westford, MA";
} else if (officename == "FRE"){
fullname = "Freeport, IL";
} else if (officename == "MIL"){
fullname = "Milwaukee, WI";
} else if (officename == "AVI"){
fullname = "Stevens Point, WI";
} else if (officename == "PLO"){
fullname = "Plover, WI";
} else if (officename == "MADG"){
fullname = "Madison, WI";
} else if (officename == "MADC"){
fullname = "Madison, WI";
} else if (officename == "MADR"){
fullname = "Madison, WI";
} else if (officename == "EDW"){
fullname = "Edwardsville, IL";
} else if (officename == "CHA"){
fullname = "Charlotte, NC";
These format text color based on ping after being run through some else if statements.
pingResultHTML = "<span style='color:" + pingColor + "'>" + pingResult + " (" + pingTime + " ms)</span>";
circuitPrimaryResultHTML = "<span style='color:" + linkStatusPrimaryColor + "'>" + linkStatusPrimary + " (" + linkStatusPrimaryTime+ " ms)</span>";
This is an example of the data in the txt file.
MAD,GOOD,7,GOOD,7
DAV,GOOD,30,GOOD,30
first You need to adapt data in javascript understandable form like object,map & whatever.....
then you need to just iterate over that like that-
Let Suppose data contains you map.
var rowCount=1,
table = document.getElementById("myTable"),
tbdy = document.createElement('tbody');
for (var k in data) {
var tr = document.createElement('tr');
for (var j = 0; j < 3; j++){
var td = document.createElement('td');
td.appendChild(document.createTextNode((!j)?rowCount++:(j==1)?k:device[k]));
tr.appendChild(td);
}
tbdy.appendChild(tr);
}
table.appendChild(tbdy);
I suggest use something like OOP:
function MyTable(data) {
this.data = data;
this.rows = [];
this.container = document.createElement('table');
this.body = document.createElement('tbody');
this.container.appendChild(this.body);
this.render();
}
MyTable.prototype.render = function(){
this.body.innerHTML = '';
for(var i = 0; i < this.data.length; i++){
this.rows.push(new MyRow(this.data[i]));
}
for(var j = 0; j < this.rows.length; j++) {
this.body.appendChild(this.rows[j].container);
}
}
MyTable.prototype.setData= function(data){
this.data = data;
this.rows = [];
this.render();
}
function MyRow(data) {
this.container = document.createElement('tr');
var name = document.createElement('td');
name.innerHTML = data.name;
this.container.appendChild(name);
}
var myTable = new MyTable([{name: 'Joe'}, {name: 'Pit'}]);
document.body.appendChild(myTable.container);
//data update:
myTable.setData([{name: 'Alex'}, {name: 'Stephan'}]);
myTable.render();

Asynchronous execution of javascript code

I am studying javascript and json but I've some problems: I have a script that works with json but the performances of what I wrote aren't that good. The code works only if I do a debug step by step with firebug or other tools and that makes me think that the execution of the code (or a part of it ... the one that creates the table as you'll see) requires too much time so the browser stops it.
The code is:
var arrayCarte = [];
var arrayEntita = [];
var arraycardbyuser = [];
function displayArrayCards() {
var richiestaEntity = new XMLHttpRequest();
richiestaEntity.onreadystatechange = function() {
if(richiestaEntity.readyState == 4) {
var objectentityjson = {};
objectentityjson = JSON.parse(richiestaEntity.responseText);
arrayEntita = objectentityjson.cards;
}
}
richiestaEntity.open("GET", "danielericerca.json", true);
richiestaEntity.send(null);
for(i = 0; i < arrayEntita.length; i++) {
var vanityurla = arrayEntita[i].vanity_urls[0] + ".json";
var urlrichiesta = "http://m.airpim.com/public/vurl/";
var richiestaCards = new XMLHttpRequest();
richiestaCards.onreadystatechange = function() {
if(richiestaCards.readyState == 4) {
var objectcardjson = {};
objectcardjson = JSON.parse(richiestaCards.responseText);
for(j = 0; j < objectcardjson.cards.length; j++)
arrayCarte[j] = objectcardjson.cards[j].__guid__; //vettore che contiene i guid delle card
arraycardbyuser[i] = arrayCarte;
arrayCarte = [];
}
}
richiestaCards.open("GET", vanityurla, true);
richiestaCards.send(null);
}
var wrapper = document.getElementById('contenitoro');
wrapper.innerHTML = "";
var userTable = document.createElement('table');
for(u = 0; u < arrayEntita.length; u++) {
var userTr = document.createElement('tr');
var userTdcard = document.createElement('td');
var userTdinfo = document.createElement('td');
var br = document.createElement('br');
for(c = 0; c < arraycardbyuser[u].length; c++) {
var cardImg = document.createElement('img');
cardImg.src = "http://www.airpim.com/png/public/card/" + arraycardbyuser[u][c] + "?width=292";
cardImg.id = "immaginecard";
userTdcard.appendChild(br);
userTdcard.appendChild(cardImg);
}
var userdivNome = document.createElement('div');
userdivNome.id = "diverso";
userTdinfo.appendChild(userdivNome);
var userdivVanity = document.createElement('div');
userdivVanity.id = "diverso";
userTdinfo.appendChild(userdivVanity);
var nome = "Nome: ";
var vanityurl = "Vanity Url: ";
userdivNome.innerHTML = nome + arrayEntita[u].__title__;
userdivVanity.innerHTML = vanityurl + arrayEntita[u].vanity_urls[0];
userTr.appendChild(userTdcard);
userTr.appendChild(userTdinfo);
userTable.appendChild(userTr);
}
wrapper.appendChild(userTable);
}
The problem is that the code that should make the table doesn't wait for the complete execution of the code that works with the json files. How can I fix it? I would prefer,if possible, to solve that problem with something easy, without jquery and callbacks (I am a beginner).
You'll have to move som code around to make that work. at first, split it up in some functions, then it is easier to work with. I dont know if it works, but the idea is that first it loads the arrayEntita. When that is done, it fills the other 2 arrays. And when the last array has been filled, it builds the table.
var arrayCarte = [];
var arrayEntita = [];
var arraycardbyuser = [];
function displayArrayCards() {
var richiestaEntity = new XMLHttpRequest();
richiestaEntity.onreadystatechange = function () {
if (richiestaEntity.readyState == 4) {
var objectentityjson = {};
objectentityjson = JSON.parse(richiestaEntity.responseText);
arrayEntita = objectentityjson.cards;
BuildArrayEntita();
}
}
richiestaEntity.open("GET", "danielericerca.json", true);
richiestaEntity.send(null);
}
function BuildArrayEntita() {
for (i = 0; i < arrayEntita.length; i++) {
var vanityurla = arrayEntita[i].vanity_urls[0] + ".json";
var urlrichiesta = "http://m.airpim.com/public/vurl/";
var richiestaCards = new XMLHttpRequest();
richiestaCards.onreadystatechange = function () {
if (richiestaCards.readyState == 4) {
var objectcardjson = {};
objectcardjson = JSON.parse(richiestaCards.responseText);
for (j = 0; j < objectcardjson.cards.length; j++)
arrayCarte[j] = objectcardjson.cards[j].__guid__; //vettore che contiene i guid delle card
arraycardbyuser[i] = arrayCarte;
arrayCarte = [];
//If it is the last call to populate arraycardbyuser, build the table:
if (i + 1 == arrayEntita.length)
BuildTable();
}
}
richiestaCards.open("GET", vanityurla, true);
richiestaCards.send(null);
}
}
function BuildTable() {
var wrapper = document.getElementById('contenitoro');
wrapper.innerHTML = "";
var userTable = document.createElement('table');
for (u = 0; u < arrayEntita.length; u++) {
var userTr = document.createElement('tr');
var userTdcard = document.createElement('td');
var userTdinfo = document.createElement('td');
var br = document.createElement('br');
for (c = 0; c < arraycardbyuser[u].length; c++) {
var cardImg = document.createElement('img');
cardImg.src = "http://www.airpim.com/png/public/card/" + arraycardbyuser[u][c] + "?width=292";
cardImg.id = "immaginecard";
userTdcard.appendChild(br);
userTdcard.appendChild(cardImg);
}
var userdivNome = document.createElement('div');
userdivNome.id = "diverso";
userTdinfo.appendChild(userdivNome);
var userdivVanity = document.createElement('div');
userdivVanity.id = "diverso";
userTdinfo.appendChild(userdivVanity);
var nome = "Nome: ";
var vanityurl = "Vanity Url: ";
userdivNome.innerHTML = nome + arrayEntita[u].__title__;
userdivVanity.innerHTML = vanityurl + arrayEntita[u].vanity_urls[0];
userTr.appendChild(userTdcard);
userTr.appendChild(userTdinfo);
userTable.appendChild(userTr);
}
wrapper.appendChild(userTable);
}
i dont know if this check:
if (i + 1 == arrayEntita.length)
BuildTable();
but else you have to check if alle responseses have returned before executing buildtable();
AJAX requests are asynchronous. They arrive at an unknown period during execution and JavaScript does not wait for the server to reply before proceeding. There is synchronous XHR but it's not for ideal use. You'd lose the whole idea of AJAX if you do so.
What is usually done is to pass in a "callback" - a function that is executed sometime later, depending on when you want it executed. In your case, you want the table to be generated after you receive the data:
function getData(callback){
//AJAX setup
var richiestaEntity = new XMLHttpRequest();
//listen for readystatechange
richiestaEntity.onreadystatechange = function() {
//listen for state 4 and ok status (200)
if (richiestaEntity.readyState === 4 && richiestaEntity.status === 200) {
//execute callback when data is received passing it
//what "this" is in the callback function, as well as
//the returned data
callback.call(this,richiestaEntity.responseText);
}
}
richiestaEntity.open("GET", "danielericerca.json"); //third parameter defaults to true
richiestaEntity.send();
}
function displayArrayCards() {
//this function passed to getData will be executed
//when data arrives
getData(function(returnedData){
//put here what you want to execute when getData receives the data
//"returnedData" variable inside this function is the JSON returned
});
}
As soon as you have made the ajax call, put all of the rest of the code inside the readystatechange function. This way, it will execute everything in order.
Edit: #Dappergoat has explained it better than I can.

Categories

Resources