successfully parsed my .json file but there is an error - javascript

I've been continuing my work on a drag and drop page that will parse and display the json data.
I was able to parse the .json file and showed it in console but at the end there is an error showing up (Please refer on the screenshot below). Did I miss anything from my code? Thank you in advance!
JSFiddle : https://jsfiddle.net/vy19a7sf/2/
(function() {
var dropzone = document.getElementById("dropzone");
dropzone.ondrop = function(event) {
event.preventDefault();
this.className = "dropzone";
console.log(event.dataTransfer.files[0]);
var fileInput = document.getElementById("dropzone");
var fileDisplayArea = document.getElementById("displayarea");
var file = event.dataTransfer.files[0]
var textType = "";
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(read) {
// fileDisplayArea.innerText = reader.result;
var json = reader.result;
for(var num = 0; num < json.length; num++) {
obj = JSON.parse(json);
// console.log(obj["value"][num]);
console.log(obj["value"][num]["changesetId"]);
console.log(obj["value"][num]["author"]["displayName"]);
console.log(obj["value"][num]["createdDate"]);
console.log(obj["value"][num]["comment"]);
}
}
reader.readAsText(file);
}
else {
// fileDisplayArea.innerText = "File not supported!";
console.log("File not supported!")
}
}
dropzone.ondragover = function() {
this.className = "dropzone dragover";
return false;
};
dropzone.ondragleave = function() {
this.className = "dropzone";
return false;
};
}())
.dropzone {
display: flex;
line-height: 300px;
justify-content: center;
border: 2px dashed #ccc;
color: #ccc;
}
.dropzone.dragover {
border-color: #000;
color: #000;
}
.displayarea {
height: 200px;
width: 100%;
color: #000;
padding: 20px;
background-color: #e7e7e7;
overflow-x: auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css" />
<link rel="stylesheet" href="/css/styles.css" />
<link rel="stylesheet" href="/changesets/css/styles.css" />
<title>Code Metrics Tool</title>
</head>
<body>
<header>
<div>
Code Metrics Tool
</div>
</header>
<main>
<h2>Changesets</h2>
<div class="dropzone" id="dropzone">Drop .json files here to convert</div>
</main>
<footer>
</footer>
<script src="/changesets/js/dragdrop.js"></script>
</body>
</html>
SCREENSHOT Console log was successfully printed, but at the end there is an error showing up
JSON File
{
"count": 2,
"value": [
{
"changesetId": 1456,
"url": "https://.../changesets/1456",
"author": {
"displayName": "--",
"url": "https://.../0e79980d-2df8-47b2-9aa3-4a7a118f1c90",
"id": "0e79980d-2df8-47b2-9aa3-4a7a118f1c90",
"uniqueName": "--",
"imageUrl": "https://.../identityImage?id=0e79980d-2df8-47b2-9aa3-4a7a118f1c90"
},
"checkedInBy": {
"displayName": "--",
"url": "https://.../0e79980d-2df8-47b2-9aa3-4a7a118f1c90",
"id": "0e79980d-2df8-47b2-9aa3-4a7a118f1c90",
"uniqueName": "--",
"imageUrl": "https://.../identityImage?id=0e79980d-2df8-47b2-9aa3-4a7a118f1c90"
},
"createdDate": "2018-02-28T11:20:36.52Z",
"comment": "fixed problems",
"commentTruncated": true
},
{
"changesetId": 1451,
"url": "https://.../changesets/1451",
"author": {
"displayName": "--",
"url": "https://.../f62e6531-cb28-6ebb-bb5c-1663549c6165",
"id": "f62e6531-cb28-6ebb-bb5c-1663549c6165",
"uniqueName": "--",
"imageUrl": "https://.../identityImage?id=f62e6531-cb28-6ebb-bb5c-1663549c6165"
},
"checkedInBy": {
"displayName": "--",
"url": "https://.../f62e6531-cb28-6ebb-bb5c-1663549c6165",
"id": "f62e6531-cb28-6ebb-bb5c-1663549c6165",
"uniqueName": "--",
"imageUrl": "https:///identityImage?id=f62e6531-cb28-6ebb-bb5c-1663549c6165"
},
"createdDate": "2018-02-26T11:47:42.233Z",
"comment": "Added an item",
"commentTruncated": true
}
]
}

As Patrick Evans commented, json.length is not the length of the array in "value".
You also don't want to use obj = JSON.parse(json) inside that loop, you only need to parse it once.
To solve this issue you described, you need to get the actual ids inside the "value" array.
let valueArray = obj.value;
valueArray.forEach(function(vel){
console.log(vel.changesetId);
console.log(vel.author);
//etc..
});

Related

Display JSON file on ChartJS

I am trying to display JSON data on a doughnut chart using chartJS. My issue is that it will only display one piece of data from the JSON. How do I get all pieces of data to display? Code is below:
const xmlhttp = new XMLHttpRequest();
const url = 'https://api.npoint.io/c189874f4d8f7c14d816';
xmlhttp.open('GET', url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
const datapoints = JSON.parse(this.responseText);
var labels1 = datapoints.activePositions.map(function(e) {
return e.positions;
});
var data1 = datapoints.activePositions.map(function(e) {
return e.holders;
});
const insitutionalholders = document.getElementById('institutional_activepositions_piechart').getContext('2d');
const insitutionalholdersforstock = new Chart(insitutionalholders, {
type: 'doughnut',
data: {
labels: labels1,
datasets: [{
label: 'yooooo',
data: data1,
backgroundColor: [
'rgba(0, 255, 255, 0.2)'
],
borderColor: [
'rgba(0, 255, 255, 1)'
],
borderWidth: 2.5
}]
}
});
}
}
Below is my JSON data (the data is need is from "activePositions"):
{
"activePositions": [
{
"positions": "Increased Positions",
"holders": "1,799",
"shares": "201,837,184"
},
{
"positions": "Decreased Positions",
"holders": "2,313",
"shares": "226,754,389"
},
{
"positions": "Held Positions",
"holders": "306",
"shares": "8,979,550,845"
},
{
"positions": "Total Institutional Shares",
"holders": "4,418",
"shares": "9,408,142,418"
}
],
"newSoldOutPositions": [
{
"positions": "New Positions",
"holders": "122",
"shares": "55,880,226"
},
{
"positions": "Sold Out Positions",
"holders": "74",
"shares": "8,818,741"
}
]
}
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="draftfortesting.css">
</head>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.9.1/dist/chart.min.js"></script>
<body>
<div class="myChartDiv">
<canvas id="institutional_activepositions_piechart"></canvas>
</div>
</body>
<script src="AAPLpiechart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.9.1/dist/chart.min.js"></script>
What's weird to me is that the data that shows is the third piece inside the JSON, so I'm not sure why that's happened.
The issue seems to be related to the value of holders field of data points.
The are not numbers having the "comma" (for instance "holders": "1,799",)
You could try to remove the comma and parsing as float:
var labels1 = datapoints.activePositions.map(function(e) {
return e.positions;
});
var data1 = datapoints.activePositions.map(function(e) {
return parseFloat(e.holders.replace(',','')); // remove comma
});
EDIT: to remove the "total" item:
const activePositions = datapoints.activePositions.filter(e => !e.positions.startsWith('Total'));
var labels1 = activePositions.map(function(e) {
return e.positions;
});
var data1 = activePositions.map(function(e) {
return parseFloat(e.holders.replace(',',''));
});

Weird behaviour while changing the parent of multiple elements

my element structure looks something like this (simplified):
#Element Holder
#Element Data
#Element Holder
#Element Data
#Element Holder.
#Element Data
#Element Holder
#Element Data
Think of it as something of a file structure, where a File/Folder is equal to #Element Holder and #Element Data is each files/folders style content (icons etc.)
Im trying to move an array of type #ElementData to the Dropzone element, so far Ive tried versions of this:
for(i = 0; i < ElementDataArray.length; i++){
Dropzone.appendChild(ElementDataArray[i].parentNode)
}
but this only works for the first element of the array (other elements stay unchanged).
Im guessing there is something going on in the DOM that Im not aware of, but currently Im just a bit lost
UPDATE
As requested by Barmar here is the stack snippet, Im sorry for this code dump, but the simplified version worked as expected, however I have no clue what went wrong here, the part that gives me headaches is located in the drop event listener
How to reproduce the issue:
run the snippet, CTRL select two or more items of the same type (2+ files or 2+ folders) and drag them into a random folder or the parent directory (gray zone below all the files and folders)
Current Result:
only one item is moved, the other items stay unchanged (moved items higlighted with red)
Expected Result: All the selected items get transferred
var file_manager = document.getElementById('file-manager')
var dragged;
var dropzone = undefined
var items = []
var dataSet = [{
"_id": "60f5b94f7e7e030d80888dd4",
"name": "EEEEE",
"path": [],
"dateCreated": "2021-07-19T17:41:35.290Z",
"isFile": true
},
{
"_id": "60f5e8ac429e454e341534fb",
"name": "pog",
"path": [],
"dateCreated": "2021-07-19T21:03:40.888Z",
"isFile": false
},
{
"_id": "60f5f7aad1b95b51840e98ca",
"name": "poem",
"path": [{
"name": "pog",
"_id": "60f5e8ac429e454e341534fb"
}],
"dateCreated": "2021-07-19T22:07:38.044Z",
"isFile": true
},
{
"_id": "60f8ae19a44c7048306fdd8b",
"name": "New folder",
"path": [],
"dateCreated": "2021-07-21T23:30:33.580Z",
"isFile": false
},
{
"_id": "60f8ae1ba44c7048306fdd8d",
"name": "new",
"path": [{
"name": "New folder",
"_id": "60f8ae19a44c7048306fdd8b"
}],
"dateCreated": "2021-07-21T23:30:35.846Z",
"isFile": false
},
{
"_id": "60f8b4708a065c4f3c068689",
"name": "New file",
"path": [{
"name": "New folder",
"_id": "60f8b4718a065c4f3c06868a"
},
{
"name": "new",
"_id": "60f8ae1ba44c7048306fdd8d"
},
{
"name": "New folder",
"_id": "60f8ae19a44c7048306fdd8b"
}
],
"dateCreated": "2021-07-21T23:57:36.198Z",
"isFile": true
},
{
"_id": "60f8b4718a065c4f3c06868a",
"name": "New folder",
"path": [{
"name": "new",
"_id": "60f8ae1ba44c7048306fdd8d"
},
{
"name": "New folder",
"_id": "60f8ae19a44c7048306fdd8b"
}
],
"dateCreated": "2021-07-21T23:57:37.204Z",
"isFile": false
},
{
"_id": "60f9b4117a7946585c8487ba",
"name": "New file",
"path": [{
"name": "New folder",
"_id": "60f8b4718a065c4f3c06868a"
},
{
"name": "new",
"_id": "60f8ae1ba44c7048306fdd8d"
},
{
"name": "New folder",
"_id": "60f8ae19a44c7048306fdd8b"
}
],
"dateCreated": "2021-07-22T18:08:17.771Z",
"isFile": true
},
{
"_id": "60fa3abc8612930538c4ecb4",
"name": "New folder",
"path": [{
"name": "pog",
"_id": "60f5e8ac429e454e341534fb"
}],
"dateCreated": "2021-07-23T03:42:52.671Z",
"isFile": false
},
{
"_id": "60fa3ac68612930538c4ecb5",
"name": "no",
"path": [],
"dateCreated": "2021-07-23T03:43:02.320Z",
"isFile": false
},
{
"_id": "6100be61171bce035120d603",
"name": "mobile test",
"path": [{
"name": "no",
"_id": "60fa3ac68612930538c4ecb5"
}],
"dateCreated": "2021-07-28T02:18:09.181Z",
"isFile": true
},
{
"_id": "6100be6f171bce035120d604",
"name": "mobile test 2",
"path": [{
"name": "pog",
"_id": "60f5e8ac429e454e341534fb"
}],
"dateCreated": "2021-07-28T02:18:23.676Z",
"isFile": true
},
{
"_id": "6104088123b899c7bd4ff752",
"name": "New folder",
"path": [],
"dateCreated": "2021-07-30T14:11:13.560Z",
"isFile": false
},
]
loadFileManager()
function loadFileManager() {
file_manager.innerHTML = ''
items = []
loop(undefined, 1)
function loop(parentid, depth) {
var tmp = []
dataSet.forEach(item => {
if (item.path.length > 0) { //sub directory
if (parentid) {
if (item.path[0]._id == parentid) {
tmp.push({
item: item,
depth: depth
})
}
}
} else { //main directory
if (parentid == undefined) {
tmp.push({
item: item,
depth: depth
})
}
}
});
var folders = tmp.filter(i => i.item.isFile == false)
var files = tmp.filter(i => i.item.isFile == true)
folders.forEach(f => {
create(f.item, f.depth)
loop(f.item._id, f.depth + 1)
});
files.forEach(f => {
create(f.item, f.depth)
//loop(f.item.id, f.depth + 1)
});
}
}
function create(item, depth) {
var holder = document.createElement('div')
var name = document.createElement('span')
var data = document.createElement('div')
data.style.textIndent = (20 *depth) + 'px'
if (item.isFile) {
data.innerHTML = data.innerHTML + `
<svg class="file-icon-svg" width="13" height="15" viewBox="0 0 77 100" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M73.5 34.5192V89C73.5 93.1421 70.1421 96.5 66 96.5H11C6.85786 96.5 3.5 93.1421 3.5 89V11C3.5 6.85787 6.85787 3.5 11 3.5H42.751C44.7551 3.5 46.6759 4.30212 48.0848 5.72742L71.3338 29.2466C72.7217 30.6505 73.5 32.5451 73.5 34.5192Z" stroke="#CCCCCC" stroke-width="7"/>
<path d="M42.875 2V36H75.25" stroke="#CCCCCC" stroke-width="7"/>
</svg>
`
} else {
data.innerHTML = data.innerHTML + `
<svg class="arrow-icon-svg" width="10" height="5" viewBox="0 0 56 29" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M55.0248 6.02109L28 28.5L24 23.4976L51 1L55.0248 6.02109Z" fill="#CCCCCC"/>
<path d="M5 1L31.5786 23.6976L28 28.5L0.910334 5.79628L5 1Z" fill="#CCCCCC"/>
</svg>
<svg class="folder-icon-svg" width="15" height="20" viewBox="0 0 98 80" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M94 21.3256V71.9437C94 74.1839 92.189 76 89.9551 76H8.04494C5.81098 76 4 74.1839 4 71.9437V8.05634C4 5.81608 5.81098 4 8.04494 4H39.5183C40.5315 4 41.5079 4.38133 42.2541 5.06854L52.6028 14.5979C54.4686 16.316 56.9094 17.2693 59.4423 17.2693H89.9551C92.189 17.2693 94 19.0853 94 21.3256Z" stroke="#CCCCCC" stroke-width="7"/>
</svg>
`
}
name.innerHTML = item.name
holder.classList.add('file-manager-item', 'noselect', (item.isFile) ? 'file' : 'folder')
holder.id = item._id
data.title = item._id
data.classList.add('file-manager-item-hover')
data.draggable = true
data.onclick = function (e) {
removeClass(file_manager, 'selected-file-manager-item')
data.classList.add('selected-file-manager-item')
var nodeDepth = 0
if(e.ctrlKey){
if(data.classList.contains('ctrl-selected-file-manager-item')){
data.classList.remove('ctrl-selected-file-manager-item')
removeClass(file_manager, 'ctrl-selected-file-manager-item-removed')
data.classList.add('ctrl-selected-file-manager-item-removed')
}
else{
removeClass(file_manager, 'ctrl-selected-file-manager-item-removed')
data.classList.add('ctrl-selected-file-manager-item')
}
}
else{
getDepth(holder)
function getDepth(child) {
if (child != null) {
nodeDepth++
getDepth(child.parentNode)
}
}
nodeDepth = nodeDepth - 6
removeClass(file_manager, 'ctrl-selected-file-manager-item-removed')
removeClass(file_manager, 'ctrl-selected-file-manager-item')
data.classList.add('ctrl-selected-file-manager-item')
if(item.isFile == false) { //folder
var arrow = data.getElementsByClassName('arrow-icon-svg')[0]
var arrowStyle = getComputedStyle(arrow).transform
if (arrowStyle == 'none' || arrow.style.transform == 'rotate(0deg)') { //close folder
arrow.style.transform = 'rotate(-90deg)'
if (holder.children.length > 0) {
for (i = 1; i < holder.children.length; i++) {
holder.children[i].style.display = 'none'
}
}
} else { //open folder
arrow.style.transform = 'rotate(0deg)'
if (holder.children.length > 1) {
for (i = 1; i < holder.children.length; i++) {
holder.children[i].style.display = 'block'
}
}
}
}
}
}
data.ondblclick = function () {
console.log(item.name + ' [' + item._id + ']')
}
data.appendChild(name)
holder.appendChild(data)
if (item.path.length == 0) {
file_manager.appendChild(holder)
} else {
document.getElementById(item.path[0]._id).appendChild(holder)
holder.style.display = 'none'
}
}
file_manager.onclick = function (e) {
if (e.target.id == 'file-manager') {
removeClass(file_manager, 'ctrl-selected-file-manager-item')
removeClass(file_manager, 'selected-file-manager-item')
removeClass(file_manager, 'ctrl-selected-file-manager-item-removed')
}
}
document.body.onclick = function (e) {
if (e.target.nodeName == 'BODY') {
removeClass(file_manager, 'ctrl-selected-file-manager-item')
removeClass(file_manager, 'selected-file-manager-item')
removeClass(file_manager, 'ctrl-selected-file-manager-item-removed')
}
}
function windowItemClick(e) {
for (i = 0; i < windowItems.length; i++) {
windowItems[i].classList.remove('window-header-item-selected')
}
if (e.target.classList.contains('window-header-item-close-button')) {
e.target.parentNode.classList.add('window-header-item-selected')
} else {
e.target.classList.add('window-header-item-selected')
}
}
/* events fired on the draggable target */
document.addEventListener("drag", function (event) {
removeClass(file_manager, 'selected-file-manager-item')
}, false);
document.addEventListener("dragstart", function (event) {
var many = file_manager.getElementsByClassName('ctrl-selected-file-manager-item')
if(many.length > 0){
var includes = false
for(i = 0; i < many.length; i++){
if(many[i] == event.target){
includes = true
break
}
}
if(includes){//CTRL
for (i = 0; i < items.length; i++) {
items[i].children[0].classList.remove('selected-file-manager-item')
}
dragged = many
createCoverup(dragged.length)
}
else{//CTRL -> DRAG
removeClass(file_manager, 'ctrl-selected-file-manager-item')
for (i = 0; i < items.length; i++) {
items[i].children[0].classList.remove('selected-file-manager-item')
}
event.target.classList.add('selected-file-manager-item')
dragged = []
dragged.push(event.target)
createCoverup(dragged[0].children[dragged[0].children.length - 1].innerText)
}
}
else{//DRAG
for (i = 0; i < items.length; i++) {
items[i].children[0].classList.remove('selected-file-manager-item')
}
event.target.classList.add('selected-file-manager-item')
dragged = []
dragged.push(event.target)
createCoverup(dragged[0].children[dragged[0].children.length - 1].innerText)
}
function createCoverup(text){
var coverup = document.createElement('span')
coverup.innerText = text
coverup.classList.add('coverup')
coverup.style.position = "absolute";
coverup.style.top = "0px";
coverup.style.right = "-300px";
document.body.appendChild(coverup);
event.dataTransfer.setDragImage(coverup, -10, -10);
}
}, false);
document.addEventListener("dragend", function (event) {
// reset the transparency
event.target.style.opacity = "";
}, false);
/* events fired on the drop targets */
document.addEventListener("dragover", function (event) {
// prevent default to allow drop
event.preventDefault();
}, false);
document.addEventListener("dragenter", function (e) {
dropzone = undefined
var found = document.elementsFromPoint(e.clientX, e.clientY)
removeClass(document, 'hovered-folder')
removeClass(document, 'hovered-main')
if (found.length > 3) {
for (i = 0; i < found.length; i++) {
if (found[i].classList.contains('folder')) {
var highlight = true
for (x = 0; x < dragged.length; x++) {
if (dragged[x].parentNode.parentNode == found[i] || dragged[x].parentNode == found[i] || dragged[x].parentNode.contains(found[i])) {
highlight = false
break
}
}
if (highlight) {
found[i].classList.add('hovered-folder')
dropzone = found[i]
}
return
}
}
} else if (found[0].id == 'file-manager') {
for (x = 0; x < dragged.length; x++) {
if (dragged[x].parentNode.parentNode.id != 'file-manager') {
found[0].classList.add('hovered-main')
dropzone = found[0]
return
}
}
}
}, false);
document.addEventListener("drop", function (event) {
event.preventDefault();
file_manager.classList.remove('hovered-main')
removeClass(file_manager, 'hovered-folder')
if (dropzone) {
var depth = 0
var path = []
getDepth(dropzone)
function getDepth(child){
if(child != null){
if(child.id){
if(child.id != 'file-manager'){
var v = dataSet.find(data => data._id == child.id)
path.push({"name":v.name, "_id":v._id})
}
}
depth++
getDepth(child.parentNode)
}
}
depth = depth - 4
for(i = 0; i < dragged.length; i++){
var currentDragged = dragged[i].parentNode
if(currentDragged.classList.contains('folder')){
dropzone.insertBefore(currentDragged, dropzone.children[1]);
}
else{
dropzone.appendChild(currentDragged)
}
loop(currentDragged, depth + 1)
function loop(element, currentDepth){
var tmp = []
element.children[0].style.textIndent = (20 * (currentDepth)) + 'px'
element.children[0].style.color = 'red'
for(x = 1; x < element.children.length; x++){
tmp.push(element.children[x])
}
tmp.forEach(t => {
loop(t, currentDepth + 1)
});
}
}
var arrow = dropzone.getElementsByClassName('arrow-icon-svg')[0]
arrow.style.transform = 'rotate(0deg)'
for (x = 1; x < dropzone.children.length; x++) {
dropzone.children[x].style.display = 'block'
}
dropzone = undefined
}
}, false);
function removeClass(element, classname) {
let x = element.getElementsByClassName(classname);
[...x].forEach(x => x.classList.remove(classname));
}
body {
background-color: black;
margin: 0;
overflow-x: hidden;
}
:root {
color-scheme: dark;
}
.noselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.hovered-folder .file-manager-item-hover{
background-color: #08574F !important;
}
.hovered-main{
background-color: #08574F !important;
}
/*#region file manager*/
#file-manager{
width: 300px;
max-height: calc(100vh - 520px);
overflow-y: auto;
overflow-x: hidden;
scrollbar-color: #202020 #101010;
scrollbar-width: thin;
padding-bottom: 200px;
background-color: #101010;
}
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #101010;
}
::-webkit-scrollbar-thumb {
background: #202020;
}
::-webkit-scrollbar-thumb:hover {
background: #353535;
}
#file-manager:hover .file-manager-line{
opacity: 1;
}
.file-manager-item{
background-color: #101010;
width: 100%;
font-smooth: always;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-size: 14px;
color: #dfdfdf;
cursor: pointer;
-webkit-tap-highlight-color: transparent;/*disable blue tap highlight*/
}
.selected-file-manager-item{
background-color: #202020;
-webkit-box-shadow: inset 0px 0px 0px 1px #009688;
box-shadow: inset 0px 0px 0px 1px #009688;
}
.file-manager-item-hover{
width: 100%;
height: 20px;
}
.file-manager-item-hover:hover{
background-color: #404040;
}
.file-manager-line{
width: 1px;
height: 20px;
background-color: #333333;
opacity: 0;
transition: .15s;
float: left;
margin-left: 12px;
}
.selected-file-manager-line{
background-color: #585858 !important;
}
.file-icon-svg {
margin-bottom: -2.5px;
}
.file-icon-svg path {
stroke: #dfdfdf;
}
.folder-icon-svg {
margin-bottom: -4px;
margin-left: -1px;
}
.folder-icon-svg path {
stroke: #dfdfdf;
}
.arrow-icon-svg{
transform: rotate(-90deg);
margin-bottom: 3px !important;
margin-left: -12px;
}
.coverup {
width: auto;
height: auto;
z-index: 2;
background-color: #202020 !important;
-webkit-box-shadow: inset 0px 0px 0px 1px #009688;
box-shadow: inset 0px 0px 0px 1px #009688;
color: #dfdfdf;
font-smooth: always;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-size: 14px;
padding-left: 4px;
padding-right: 4px;
}
/*#endregion*/
.ctrl-selected-file-manager-item, .ctrl-selected-file-manager-item:hover{
background-color: #202020;
}
.ctrl-selected-file-manager-item-removed, .ctrl-selected-file-manager-item-removed:hover{
background-color: #070707;
}
.test{
background-color: red !important;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/window.css">
<title>Document</title>
</head>
<body>
<div id="file-manager"></div>
<div id="coverup"></div>
<script src="/script.js"></script>
</body>
</html>

Connect a smart contract to HTML code via javascript

I'm trying to follow this example to build a webpage that can interact with a smart contract.
It uses this code in remix:
pragma solidity ^0.4.18;
contract Coursetro {
string fName;
uint age;
function setInstructor(string _fName, uint _age) public {
fName = _fName;
age = _age;
}
function getInstructor() public constant returns (string, uint) {
return (fName, age);
}
}
And this code which I have set up in visual studio code:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="main.css">
<!-- <script src="./node_modules/web3/dist/web3.min.js"></script> -->
<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js#1.0.0-beta.36/dist/web3.min.js"></script>
</head>
<body>
<div class="container">
<h1>Coursetro Instructor</h1>
<h2 id="instructor"></h2>
<label for="name" class="col-lg-2 control-label">Instructor Name</label>
<input id="name" type="text">
<label for="name" class="col-lg-2 control-label">Instructor Age</label>
<input id="age" type="text">
<button id="button">Update Instructor</button>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script>
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
web3.eth.defaultAccount = web3.eth.accounts[0];
var CoursetroContract = web3.eth.contract([
{
"constant": false,
"inputs": [
{
"name": "_fName",
"type": "string"
},
{
"name": "_age",
"type": "uint256"
}
],
"name": "setInstructor",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "getInstructor",
"outputs": [
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]);
var Coursetro = CoursetroContract.at('0x0CF6A859635A0729d14b524d05619c7162A102bd');
console.log(Coursetro);
Coursetro.getInstructor(function(error, result){
if(!error)
{
$("#instructor").html(result[0]+' ('+result[1]+' years old)');
console.log(result);
}
else
console.error(error);
});
$("#button").click(function() {
Coursetro.setInstructor($("#name").val(), $("#age").val());
});
</script>
</body>
</html>
When I try to pull it up on the local host I've set it up on. localhost:8545, it gives me a 400 Bad Request with this in the console:
So I tried using an http-server command which successfully set up a site I can visit, but I am receiving these errors in the console:
Just wondering if anyone has had this issues before and knows how to fix them? Or if there is something I've missed and that's why I'm getting the errors.

Trying to format results from json file into html

I am working on a simple ajax, javascript and php(json data feed) just to learn . I am a little stuck in that I am attempting to capitalize the first letter of one of the results from the json file....temp under the main obj needs to read Temp: on the html page. I tried using the function but its not erroring out but its not working at the same time. Secondly I want to move the results of either the DOM queries to the center of the page either through css or via js...I have been unsucessful at the css way.,perhaps I do not understand style as it pertains to onload? If anyone could maybe point out the correct way to implement I would appreciate it. Here is my code: an html file, css file, php file and javascript.
Thanks in advance everyone.
<body>
<h1 class="title">Todays Weather Forecast</h1>
<p class="sub">Click the button the check the local weather.</p>
<button class="demo-centered" type="button" onclick="loadPhp()">Check Weather</button><br><br>
<div id="content"></div>
<div id="content2"></div>
</body>
</html>
----------------------CSS---------------------------------------
#import url('https://fonts.googleapis.com/css2?
family=Oxygen&family=Roboto+Mono&family=Source+Code+Pro&display=swap');
/* font-family: 'Source Code Pro', monospace; */
.title {
text-align: center;
font-family: 'Oxygen', sans-serif;
}
#demo {
text-align: center;
font-family: 'Roboto Mono', monospace;
}
.demo-centered {
margin: 0;
position: absolute;
left: 45%;
}
.sub {
font-family: 'Source Code Pro', monospace;
text-align: center;
}
body {
background-image: url(./dave-herring-G5C-CsrmXak-unsplash.jpg);
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
---------------------------------PHP File-----------------------------
{
"coord": {
"lon": -116.8,
"lat": 33.03
},
"weather": [{
"id": 802,
"main": "Clouds",
"description": "scattered clouds",
"icon": "03d"
}],
"base": "stations",
"main": {
"temp": 293.73,
"feels_like": 289.89,
"temp_min": 289.26,
"temp_max": 295.93,
"pressure": 1016,
"humidity": 52
},
"visibility": 16093,
"wind": {
"speed": 5.7,
"deg": 260
},
"clouds": {
"all": 40
},
"dt": 1589408840,
"sys": {
"type": 1,
"id": 5686,
"country": "US",
"sunrise": 1589374130,
"sunset": 1589423903
},
"timezone": -25200,
"id": 5391832,
"name": "San Diego County",
"cod": 200
}
-----------------------Javascript File ---------------------------
function loadPhp() {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status === 200) {
var responseObject = JSON.parse(xhr.responseText);
var newContent = '';
var newContent2 = '';
for (var i = 0; i < responseObject.weather.length; i++) {
newContent += responseObject.weather[i].description;
}
for (var x in responseObject.main){
if (x === "temp"){
function capFirst(word){
return word.charAt(0).toUpperCase() + word.slice(1);
}
capFirst(x);
var z = responseObject.main[x];
z = Math.round((z - 273.15) * 1.8) + 32;
document.getElementById('content2').innerHTML = (x + ':' +z);
}
}
document.getElementById('content').innerHTML = "Description: " + newContent;
}
};
xhr.open('GET', 'demo.php', true);
xhr.send(null);
}
To fix the capitalization, change your code to
function capFirst(word){
return word.charAt(0).toUpperCase() + word.slice(1);
}
var capitalizedX = capFirst(x); //store returned value in a variable
......
document.getElementById('content2').innerHTML += (capitalizedX + ':' +z);

have Json data in a url want to output to html page in a table

I am a complete beginner so be easy, I have Json codein a URL Link on Amazon AWS and I want to be able to fetch the data and output it to a table on a HTML page can you help me plz. As you can see below the html code, the JS code and sample information I want to pull from the data in the JS URL link
Code below
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="http://fonts.googleapis.com/css?family=Fjalla+One|Cantarell:400,400italic,700italic,700" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="styles.css">
<title>Convert JSON Data to HTML Table Example</title>
<style>
table, th, td
{
margin:10px 0;
border:solid 1px #333;
padding:2px 4px;
font:15px Verdana;
}
th {
font-weight:bold;
}
</style>
</head>
<body>
<TITLE>"Country information"</TITLE>
<h2>Country information </h2>
<section class="content">
<div class="row">
<div class="box">
<div class="box-body">
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
</div>
</div>
<script>
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON('https://url.json', function(err, data) {
if (err != null) {
console.error(err);
} else {
var text = `Name: ${data.name}
area: ${data.area}
borders: ${data.borders}`
console.log(text);
}
});
`Sample json file on url I want to display in HTML
{
"name": "Angola",
"altSpellings": [
"AO",
"República de Angola",
"ʁɛpublika de an'ɡɔla"
],
"area": 1246700,
"borders": [
"COG",
"COD",
"ZMB",
"NAM"
],
"callingCodes": [
"244"
],
"capital": "Luanda",
"currencies": [
"AOA"
],
"demonym": "Angolan",
"flag": "https://en.wikipedia.org/wiki/Flag_of_Angola#/media/File:Flag_of_Angola.svg",
"ISO": {
"alpha2": "AO",
"alpha3": "AGO"
},
"languages": [
"pt"
],
"latlng": [
-12.5,
18.5
],
"nativeName": "Angola",
"population": 24383301,
"region": "Africa",
"subregion": "Middle Africa",
"timezones": [
"UTC+01:00"
],
"translations": {
"de": "Angola",
"es": "Angola",
"fr": "Angola",
"ja": "アンゴラ",
"it": "Angola"
},
"wiki": "http://en.wikipedia.org/wiki/angola",
"hemisphere": [
"Southern",
"Eastern"
]
},`
I use something like this for building a html table out of JSON using JS
var _table_ = document.createElement('table'),
_tr_ = document.createElement('tr'),
_th_ = document.createElement('th'),
_td_ = document.createElement('td');
_table_.classList.add('table')
function buildHtmlTable(arr) {
var table = _table_.cloneNode(false),
columns = addAllColumnHeaders(arr, table);
for (var i=0, maxi=arr.length; i < maxi; ++i) {
var tr = _tr_.cloneNode(false);
for (var j=0, maxj=columns.length; j < maxj ; ++j) {
var td = _td_.cloneNode(false);
cellValue = arr[i][columns[j]];
td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
}
function addAllColumnHeaders(arr, table)
{
var columnSet = [],
tr = _tr_.cloneNode(false);
for (var i=0, l=arr.length; i < l; i++) {
for (var key in arr[i]) {
if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key)===-1) {
columnSet.push(key);
console.log(columnSet)
var th = _th_.cloneNode(false);
th.appendChild(document.createTextNode(key));
tr.appendChild(th);
}
}
}
table.appendChild(tr);
return columnSet;
}
then I run this with the returned JSON:
document.getElementById('yourDIV').appendChild(buildHtmlTable(res));
build your api request like this:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Response comes through here
}
};
xhttp.open("GET", "/api/url/", true);
xhttp.send();
Then if you only want to push those 3 objects through to the table, create an array then build the table with those objects (not tested)
// Response comes through here
var obj = []
var data = xhttp.responseText
obj.push(data.name, data.area, data.borders)
document.getElementById('yourDIV').appendChild(buildHtmlTable(data));
Check out this JSfiddle example I did: https://jsfiddle.net/7dvudr5q/5/

Categories