I'm having problems using readings from my json file to fill in the chart. I found a function from here that allows me to pass the api url and returns the JSON data and that works, I then decided to loop through the JSON array adding each reading in an array and then passing that array into the chart function but when I load the page the chart is empty, here is the code `
<!DOCTYPE html>
<html lang="en">
<head>
<script src="Chart.js"></script>
</head>
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<div id="result"></div>
<script>
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
var json = getJSON('http://ec2-54-152-138-146.compute-1.amazonaws.com:9000/system/listSystems').then(function(data) {
alert(data.data[0].waterLevel);
var chartData =[];
for (var i = 0; i < data.length; i++){
chartData.push(data.data[i].waterLevel);
}
alert(chartData);
var barData = {
labels: ['Italy', 'UK', 'USA', 'Germany', 'France', 'Japan'],
datasets: [
{
label: '2010 customers #',
fillColor: '#382765',
data: chartData
},
{
label: '2014 customers #',
fillColor: '#7BC225',
data: chartData
}
]
};
var context = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(context).Bar(barData)
result.innerText = data.data; //display the result in an HTML element
},
function(status) { //error detection....
alert('Something went wrong.');
});</script>
</body>
</html>
Your loop is incorrect, look at the stop condition in the for cycle.
You have to use data.data.length instead of data.length:
For reference:
for (var i = 0; i < data.data.length; i++)
Change
for (var i = 0; i < data.length; i++)
to
for (var i = 0; i < data.data.length; i++)
Related
I am trying to extract data from a CSV with JavaScript and then put these values into an array and display it. My csv will have multiple rows (5 or more). So far i am trying to use a jquery library to help extract the data. I couldn't get the script to display anything when I ran it. I am new to Javascript so wasn't sure how to do this and how to take the extracted data and put it into an array.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title> Testing Orders</title>
</head> <body>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "tester excel.csv",
dataType: "text",
success: function(data) {processData(data);}
});
});
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length === headers.length) {
var tarr = [];
for (var j=0; j<headers.length; j++) {
tarr.push(headers[j]+":"+data[j]);
}
lines.push(tarr);
}
}
// alert(lines);
// console.log("tester excel.txt");
}
function getData() {
if (data == ""){
return 'DataNotReady';
}else {
}
}
windows.prompt(processData);
</script>
</body>
</html>`
I have the following code. It seems to work fine in Firefox but I get the uncaught type error in Chrome. What am I missing?
$(document).ready(function() {
$('#btn').click(function() {
var request = new XMLHttpRequest();
let url = `https://comicvine.gamespot.com/api/characters/?api_key=[apikey]`;
request.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var response = JSON.parse(this.responseText);
getElements(response);
}
}
request.open("GET", url, true);
request.overrideMimeType('text/xml');
request.send();
alert(request.status);
alert(request.statusText);
var xml = request.responseXML;
var table;
var users = xml.getElementsByTagName("character");
for (var i = 0; i < users.length; i++) {
var user = users[i];
var names = user.getElementsByTagName("name");
var name= user.getElementsByTagName("real_name");
for (var j = 0; j < names.length; j++) {
alert(names[j].childNodes[0].nodeValue);
}
}
document.getElementById("results").innerHTML = table;
});
});
I can view the data in Firefox, however nothing is displayed in Chrome.
You are attempting to get the response before it is given. I would use jQuery's ajax to complete the call.
$.ajax({
url: url,
type: "GET",
headers: {
"Accept": "application/xml;"
},
success: function(data, textStatus, xhr) {
alert(textStatus);
var xml = data;
var table;
var users = xml.getElementsByTagName("character");
for (var i = 0; i < users.length; i++) {
var user = users[i];
var names = user.getElementsByTagName("name");
var name = user.getElementsByTagName("real_name")
for (var j = 0; j < names.length; j++) {
alert(names[j].childNodes[0].nodeValue);
}
}
document.getElementById("results").innerHTML = table;
},
error: function(data, textStatus, xhr) {
alert("error occured\n" data.message);
}
});
I'm trying to get all not loaded elements in a webpage by including a script in the head of the index.html but I've some problems.
This is the code:
document.addEventListener('DOMContentLoaded', function () {
console.log("here");
var scripts = document.getElementsByTagName('script');
for(var i=0;i<scripts.length;i++){
scripts[i].onerror =function(message, source, lineno) {
console.log("JS: Error SCRIPT");
}
}
var imgs = document.getElementsByTagName('img');
for(var i=0;i<imgs.length;i++){
imgs[i].onerror =function(message, source, lineno) {
console.log("JS: Error IMG ");
}
}
var links = document.getElementsByTagName('link');
for(var i=0;i<links.length;i++){
links[i].onerror = function(message, source, lineno){
console.log("JS: Error CSS ");
}
}
});
I put 3 wrong CSS, Images and Scripts (they don't exist as resources) inside the HTML file where I call the script.
When I run locally the index.html I get "Error IMG" and "Error CSS".
When I run on the server I get only "Error IMG".
In both cases, I don't get "Error SCRIPT".
What I'm doing wrong?
UPDATE: This is the code
appmetrics.js
//class that store page resource data
/*
ES6
class Resource{
constructor(name,type,start,end,duration){
this.name = name;
this.type = type;
this.start = start;
this.end = end;
this.duration = duration;
}
}
*/
function Resource (name,type,start,end,duration){
this.name = name;
this.type = type;
this.start = start;
this.end = end;
this.duration = duration;
}
/*
ES6
class Errors{
constructor(name,source,line){
this.name = name;
this.source = source;
this.line = line;
}
}
*/
function Errors(name,source,line){
this.name = name;
this.source = source;
this.line = line;
}
//endpoint to send data
var endpoint = "https://requestb.in/sr8wnnsr"
var resources = Array();
var errors = Array();
var pageLoadTime;
var start = performance.now();
window.onload = function(){
pageLoadTime = performance.now()-start;
console.log("Page loading time: " + pageLoadTime);
//getting page resources and pushing them into the array
var res = performance.getEntriesByType("resource");
res.forEach(function add(item){
resources.push(new Resource(item.name,item.initiatorType,item.startTime,item.responseEnd,item.duration));
})
console.log(resources);
var jsonRes = JSON.stringify(resources);
//sendMetricToEndpoint(jsonRes);
//sendMetricToEndpoint(pageLoadTime.toString());
}
window.onerror = function(message, source, lineno) {
console.log("Error detected!" + "\nMessage: " +message +"\nSource: "+ source +"\nLine: "+ lineno);
errors.push(new Errors(message,source,lineno));
console.log(errors);
}
//Not working code
/*
document.addEventListener('DOMContentLoaded', function () {
console.log("here");
var scripts = document.getElementsByTagName('script');
for(var i=0;i<scripts.length;i++){
scripts[i].onerror =function(message, source, lineno) {
console.log("JS: Errore SCRIPT");
}
}
var imgs = document.getElementsByTagName('img');
for(var i=0;i<imgs.length;i++){
imgs[i].onerror =function(message, source, lineno) {
console.log("JS: Errore IMG ");
}
}
var links = document.getElementsByTagName('link');
for(var i=0;i<links.length;i++){
links[i].onerror = function(message, source, lineno){
console.log("JS: Errore CSS ");
}
}
});
*/
//StackOverflow solution start
var scripts = [];
for (var i = 0, nodes = document.getElementsByTagName('script'); i < nodes.length; i++) {
scripts[i] = { source: nodes[i].src, loaded: false };
nodes[i].onload = function() {
var loadedNode = this;
var index = scripts.findIndex(function(script) {
return script.source === loadedNode.src;
});
scripts[index].loaded = true;
};
}
var links = [];
for (var i = 0, nodes = document.getElementsByTagName('link'); i < nodes.length; i++) {
links[i] = { source: nodes[i].href, loaded: false };
nodes[i].onload = function() {
var loadedNode = this;
var index = links.findIndex(function(link) {
link.href === loadedNode.href;
});
links[index].loaded = true;
};
}
document.addEventListener('DOMContentLoaded', function() {
console.log("here");
scripts.filter(function(script) {
return !script.loaded;
}).forEach(function(script) {
console.log("Error loading script: " + script.source);
});
links.filter(function(link) {
return !link.loaded;
}).forEach(function(link) {
console.log("Error loading link: " + link.source);
});
// and the rest of the elements
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].onerror = function() {
console.log("Error loading image: " + this.src);
};
}
});
//StackOverflow solution stop
/**
* Function that send metric to endpoint.
*
* #param {string} endpoint Where to send data.
* #param {*} data data to send (JSON or string)
*/
function sendMetricToEndpoint(data){
console.log("Sending metrics to endpoint");
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
};
xhttp.open("POST", endpoint, true);
//xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(data);
}
index.html
<html>
<head>
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>-->
<script src="js/appmetricsmod.js"></script>
<link rel="stylesheet" href="styletests.css">
<link rel="stylesheet" href="styletestss.css">
<link rel="stylesheet" href="styletestsss.css">
<script src="js/error1.js"></script>
<script src="js/error2.js"></script>
<script src="js/error3.js"></script>
</head>
<body>
<img src="imgtest.png"></img>
<img src="imgErr1.png"></img>
<img src="imgErr2.png"></img>
<img src="imgErr3.png"></img>
<img src="http://images.centrometeoitaliano.it/wp-content/uploads/2016/11/15/l1.jpg"></img>
<div class="divtest">
hello this is a test
</div>
<script>
</script>
</body>
</html>
Sadly, you you cannot get link nor script error load with onerror event, but you can handle the loaded content, and filter which were not loaded. This is possible with the load event for the link and script tags.
var scripts = [];
for (var i = 0, nodes = document.getElementsByTagName('script'); i < nodes.length; i++) {
scripts[i] = { source: nodes[i].src, loaded: false };
nodes[i].onload = function() {
var loadedNode = this;
var index = scripts.findIndex(function(script) {
return script.source === loadedNode.src;
});
scripts[index].loaded = true;
};
}
var links = [];
for (var i = 0, nodes = document.getElementsByTagName('link'); i < nodes.length; i++) {
links[i] = { source: nodes[i].href, loaded: false };
nodes[i].onload = function() {
var loadedNode = this;
var index = links.findIndex(function(link) {
link.href === loadedNode.href;
});
links[index].loaded = true;
};
}
document.addEventListener('DOMContentLoaded', function() {
console.log("here");
scripts.filter(function(script) {
return !script.loaded;
}).forEach(function(script) {
console.log("Error loading script: " + script.source);
});
links.filter(function(link) {
return !link.loaded;
}).forEach(function(link) {
console.log("Error loading link: " + link.source);
});
// and the rest of the elements
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].onerror = function() {
console.log("Error loading image: " + this.src);
};
}
});
Hope it helps :)
Using the classes Resources and Errors above, I solved the problem by taking all the resources of the page and then removing the working ones. The result is an array of not loaded resources.
This is the code:
var res = performance.getEntriesByType("resource");
res.forEach(function add(item){
resources.push(new Resource(item.name,
item.initiatorType,
item.startTime,
item.responseEnd,
item.duration));
})
var flag = true;
var imgs = document.getElementsByTagName('img');
for(var i=0;i<imgs.length;i++){
for(var j=0;j<resources.length;j++){
if(imgs[i].src == resources[j].name){
flag = false;
}
}
if(flag && imgs[i].src){
errors.push(new Errors("RES NOT FOUND",imgs[i].src,null));
}
flag = true;
}
var scripts = document.getElementsByTagName('script');
for(var i=0;i<scripts.length;i++){
for(var j=0;j<resources.length;j++){
if(scripts[i].src == resources[j].name){
flag = false;
}
}
if(flag && scripts[i].src){
errors.push(new Errors("RES NOT FOUND",scripts[i].src,null));
}
flag = true;
}
var links = document.getElementsByTagName('link');
for(var i=0;i<links.length;i++){
for(var j=0;j<resources.length;j++){
if(links[i].src == resources[j].name){
flag = false;
}
}
if(flag && links[i].href){
errors.push(new Errors("RES NOT FOUND",links[i].href,null));
}
flag = true;
}
console.log(resources);
console.log(errors);
Here is my code I want to print out "song" property from data. Link to JSON is -> http://starlord.hackerearth.com/sureify/cokestudio
<script type="text/javascript">
var requestURL = 'http://starlord.hackerearth.com/sureify/cokestudio';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function(){
var myjsondata = request.response;
showdata(myjsondata);
}
function showdata(data){
var song_name = data;
for (i = 0; i < 3; i++) {
document.write(song_name);
document.write("<br>");
}
}
</script>
When I run it in browser I get [object Object],[object Object],[object Object],[object Object],[object Object] as OUTPUT or undefined.
Your data looks like this:
[ //the array in data
{ //the first object, e. g. data[0]
"song":"Afreen Afreen", // song => data[0].song
"url":"http://hck.re/Rh8KTk",
"artists":"Rahat Fateh Ali Khan, Momina Mustehsan",
"cover_image":"http://hck.re/kWWxUI"
},
{
"song":"Aik Alif",
"url":"http://hck.re/ZeSJFd",
"artists":"Saieen Zahoor, Noori",
"cover_image":"http://hck.re/3Cm0IX"
},
{
"song":"Tajdar e haram",
"url":"http://hck.re/wxlUcX",
"artists":"Atif Aslam",
"cover_image":"http://hck.re/5dh4D5"
}]
So to loop over one can do
var limit=Math.max(data.length,100);//max displayed number
for(var i=0;i<limit;i++){
document.write(data[i].song+"<br>");
}
Whole code:
document.write("loading...");
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
var data= JSON.parse(xhr.responseText);
var limit=Math.max(data.length,100);
for(var i=0;i<limit;i++){
document.write(data[i].song+"<br>");
}
}
};
xhr.open('GET', 'http://starlord.hackerearth.com/sureify/cokestudio', true);
xhr.send(null);
You cannot write the whole song object to the document. You should map it first:
var songNames = data.map(function(item) { return item.song; });
This will give you an array of all the names (strings), which you can write to the document:
songNames.forEach(function(songName) {
document.write(songName + '<br>');
});
You need to use JSON.stringify; and if you plan to write to document I suggest wrapping in pre tags as well to retain string format.
let data = [
{
"song":"Afreen Afreen",
"url":"http://hck.re/Rh8KTk",
"artists":"Rahat Fateh Ali Khan, Momina Mustehsan",
"cover_image":"http://hck.re/kWWxUI"
},
{
"song":"Aik Alif",
"url":"http://hck.re/ZeSJFd",
"artists":"Saieen Zahoor, Noori",
"cover_image":"http://hck.re/3Cm0IX"
},
{
"song":"Tajdar e haram",
"url":"http://hck.re/wxlUcX",
"artists":"Atif Aslam",
"cover_image":"http://hck.re/5dh4D5"
}
];
document.write('<pre>'+ JSON.stringify(data, null, '\t') + '</pre>');
You need to stringify the object to make it readable.
<html>
<body>
<script type="text/javascript">
var requestURL = 'http://starlord.hackerearth.com/sureify/cokestudio';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function(){
var myjsondata = request.response;
showdata(myjsondata);
}
function showdata(data){
var song_name = data;
for (i = 0; i < 3; i++) {
document.write(JSON.stringify(song_name));
document.write("<br>");
}
}
</script>
</body>
</html>
The response from the request is an array of json objects and you are just trying to write the return object over and over again. You need to iterate over the returned data and output each object's value. Change your showdata function as:
function showdata(data){
for (i = 0; i < 3; i++) {
document.write(data[i].song);
document.write("<br>");
}
}
Alright, so I got this xml file:
<?xml version="1.0" encoding="UTF-8" ?>
<level>
<tiles>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1000000000000001</row>
<row>1111111111111111</row>
</tiles>
</level>
and I got my XML reading code:
var xmlDoc = document.implementation.createDocument("","",null);
and
function loadXML(){
xmlDoc.load("levels/test.xml");
xmlDoc.onload = readLevel();
}
function readLevel() {
throw(xmlDoc);
if(xmlDoc.getElementsByTagName("tiles")[0].hasChildNodes()){
var rowNum = xmlDoc.getElementsByTagName("tiles").getChildNodes();
level = [];
for(var i = 0; i < rowNum; i++){
level[i] = [];
var tempStr = xmlDoc.getElementsByTagName("tiles").childNodes[i].textContent;
for(var j = 0; j < 16; j++){
level[i][j] = parceInt(tempStr.charAt(j));
}
}
}
for (var i = 0; i < level.length; i++) {
blockArray[i] = []; // Create the second level for this index
for (var j = 0; j < level[i].length; j++) {
var tempImg = new Image();
tempImg.src = "images/block" + level[i][j] + ".png";
blockArray[i][j] = new block(j * blockSize, i * blockSize, level[i][j], false, false, tempImg);
//throw('blockArray['+i+']'+j+'] = ' + level[i][j]);
}
}
}
Now why isn't this working? It constantly says xmlDoc.getElementsByTagName("tiles")[0] is undefined and that xmlDoc.getElementsByTagName("tiles").length = 0. So what am I doing wrong?
I'd use XMLHttpRequest and its responseXML property instead, which will work in all major browsers. Example:
function readLevel(xmlDoc) {
alert(xmlDoc.documentElement.tagName);
// Your existing code goes here
};
var createXmlHttpRequest = (function() {
var factories = [
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); },
function() { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); },
function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];
for (var i = 0, len = factories.length; i < len; ++i) {
try {
if ( factories[i]() ) return factories[i];
} catch (e) {}
}
})();
var xmlHttp = createXmlHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
readLevel(xmlHttp.responseXML);
}
};
xmlHttp.open("GET", "levels/test.xml", true);
xmlHttp.send(null);
According to SitePoint, all the arguments are required in createDocument. Maybe the falsy values are tripping you up.