Cannot load data from .CSV file to Amcharts - javascript

I am new to javascript and am creating a piechart which loads data from a comma separated file data.txt but I cannot see anything in the browser when I open the html file.
data.txt consists the following data -
United States,9252
China,1882
Japan,1809
Germany,1322
United Kingdom,1122
India,984
My html code is-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>amCharts examples</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script src="amcharts/amcharts.js" type="text/javascript"></script>
<script type="text/javascript">
var chart;
var dataProvider;
window.onload = function() {
createChart();
loadCSV("data.csv");
}
// method which loads external data
function loadCSV(file) {
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
}
else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load
request.open('GET', file, false);
request.send();
parseCSV(request.responseText);
}
// method which parses csv data
function parseCSV(data){
//replace UNIX new lines
data = data.replace (/\r\n/g, "\n");
//replace MAC new lines
data = data.replace (/\r/g, "\n");
//split into rows
var rows = data.split("\n");
// create array which will hold our data:
dataProvider = [];
// loop through all rows
for (var i = 0; i < rows.length; i++){
// this line helps to skip empty rows
if (rows[i]) {
// our columns are separated by comma
var column = rows[i].split(",");
// column is array now
// first item is date
var country = column[0];
// second item is value of the second column
var visits = column[1];
// third item is value of the fird column
// create object which contains all these items:
var dataObject = {country:country, visits:visits};
// add object to dataProvider array
dataProvider.push(dataObject);
}
}
// set data provider to the chart
chart.dataProvider = dataProvider;
// this will force chart to rebuild using new data
chart.validateData();
}
function createChart(){ // PIE CHART
chart = new AmCharts.AmPieChart();
// title of the chart
chart.addTitle("Visitors countries", 16);
chart.titleField = "country";
chart.valueField = "visits";
chart.sequencedAnimation = true;
chart.startEffect = "elastic";
chart.innerRadius = "30%";
chart.startDuration = 2;
chart.labelRadius = 15;
chart.pullOutEffect = "elastic";
chart.pullOutDuration = 1;
// the following two lines makes the chart 3D
chart.depth3D = 10;
chart.angle = 15;
// WRITE
chart.write("chartdiv");
}
</script>
</head>
<body>
<div id="chartdiv" style="width:600px; height:400px;"></div>
</body>
I have taken the code from http://blog.amcharts.com/2011/03/amcharts-javascript-tutorials-part-2.html and changed it according to piechart.
Please tell me what am I doing wrong.
I have placed data.txt in the same folder as the html file and have not hosted the file on a web server

You're calling loadCSV to load data.csv, but you said your data is in data.txt.

You should try to update your JS, Chrome throws this error : "AmCharts.AmPieChart is not a functioncreateChart # Pie Charts.html:75window.onload # Pie Charts.html:15"
Try to Use DATALOADER :
AmCharts.makeChart("chartdiv", {
"type": "pie",
"dataLoader": {
"url": "data/pie.csv",
"format": "csv",
"delimiter": ",",
"useColumnNames": true
},

Related

Google Annotation Chart load from CSV

I am trying to create a Google Annotation chart by loading some data from a CSV file using the example found here:
https://developers.google.com/chart/interactive/docs/gallery/annotationchart
I've tried to modify the code (using my limited JS knowledge) to load from a CSV file but I'm getting no graph.
My code so far:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type='text/javascript'>
google.charts.load('current', {'packages':['annotationchart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
$.get('test.csv', function(csvString)
{
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
arrayData = arrayData.map(function (row)
{
return
[new Date(row[0]),row[1]];
});
var data = google.visualization.arrayToDataTable(arrayData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true
};
chart.draw(data, options);
}
}
</script>
</head>
<body>
<div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>
CSV File
Date,Value1
2014-01-01,1233
2014- 01-02,1334
2014-01-03,1488
2014-01-04,1888
2014-01-05,2011
2014-01-06,1900
2014-01-07,1768
2014-01-08,2345
first, add jquery and jquery csv to your page.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
then replace the code as follows.
see comments for explanations...
// load google charts
google.charts.load('current', {
packages: ['annotationchart']
}).then(function () {
// declare data variable
var arrayData;
// get csv data
$.get('test.csv', function(csvString) {
// get csv data success, convert to an array, draw chart
arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
drawChart(arrayData);
}).fail(function () {
// get csv data failed, draw chart with hard-coded data, for example purposes
arrayData = [
['Date','Value1'],
['2014-01-01',1233],
['2014-01-02',1334],
['2014-01-03',1488],
['2014-01-04',1888],
['2014-01-05',2011],
['2014-01-06',1900],
['2014-01-07',1768],
['2014-01-08',2345],
];
drawChart(arrayData);
});
});
// draw chart
function drawChart(arrayData) {
// convert string in first column to a date
arrayData = arrayData.map(function (row) {
return [new Date(row[0]),row[1]];
});
// create google data table, chart, and options
var data = google.visualization.arrayToDataTable(arrayData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true
};
// draw chart
chart.draw(data, options);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note: you can remove the fail callback, it is for example purposes here on stack overflow...
You need to follow 3 step for this task
Fire ajax request and take csv data
Convert csv data into array
Pass csv array in google graph
Please take refrence from following example:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type='text/javascript'>
//Step 1: Get string from csv
$(document).ready(function () {
$.ajax({
type: "GET",
url: "test.csv",
dataType: "text",
success: function (data) {
//Step 2: Convert "," seprated string into array
let arrData = csvToArray(data);
//Step 3: call chart with array data
callChart(arrData);
}
});
});
//convert csv string into array function
function csvToArray(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);
}
}
return lines;
}
function callChart(arrData) {
google.charts.load('current', { 'packages': ['annotationchart'] });
google.charts.setOnLoadCallback(function () { drawChart(arrData); });
}
function drawChart(arrData) {
var data = new google.visualization.DataTable();
//Step 4: add csv your column
data.addColumn('date', 'Date');
data.addColumn('number', 'Kepler-22b mission');
//Step 5: pass your csv data as array
data.addRows(arrData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
var options = {
displayAnnotations: true
};
chart.draw(data, options);
}
</script>
</head>
<body>
<div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>

Load RSS data into global variable

I use Javascript. I want to get RSS data by API google (this link: http://www.javascriptkit.com/dhtmltutors/googleajaxfeed.shtml ), then insert the data into a Array (Global variable). But my global variable can not save data.
Inside rssfeedsetup() function, ARR_DATA (Global Array) have data. However, after load rssfeedsetup() function, ARR_DATA have no data.
Please show me, how to insert data to global variable in this case.
My code:
Head:
<head>
<title>TEST API FEED RSS</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
google.load("feeds", "1"); //Load Google Ajax Feed API (version 1)
</script>
</head>
Body:
<body>
<div id="feeddiv"></div>
<script type="text/javascript">
var ARR_DATA = []; // **I want to insert data into this array**
var feedurl = "http://rss.slashdot.org/Slashdot/slashdot";
var feedlimit = 4;
function rssfeedsetup() {
var feedpointer = new google.feeds.Feed(feedurl); //Google Feed API method
feedpointer.setNumEntries(feedlimit); //Google Feed API method
feedpointer.load(displayfeed); //Google Feed API method
}
function displayfeed(result) {
if (!result.error) {
var thefeeds = result.feed.entries;
var arr_Temporary = [];
for (var i = 0; i < thefeeds.length; i++) {
arr_Temporary[0] = thefeeds[i].title;
arr_Temporary[1] = thefeeds[i].link;
// insert RSS data into ARR_DATA.
ARR_DATA.push(arr_Temporary);
console.log('value before:', ARR_DATA); // check value of ARR_DATA, there have data exist.
}
}
}
window.onload = function () {
rssfeedsetup(); // call function
console.log('value2 after:', ARR_DATA); // check value of ARR_DATA, there is no data.
};
console.log('value2 after:', ARR_DATA); //check value of ARR_DATA, there is no data.
</script>
</body>
I have got value console:
image of firebug on firefox
Ps: Why ARR_DATA no contain data after load function rssfeedsetup()?
You can push data into the array like this:
function displayfeed(result) {
if (!result.error) {
var thefeeds = result.feed.entries;
for (var i = 0; i < thefeeds.length; i++) {
var feed = {
title: thefeeds[i].title,
link: thefeeds[i].link
};
ARR_DATA.push(feed);
}
console.log(feed);
}
}
Hope it helps

How to improve display of JSON data

I am new to JSON and JS, and have generated a JSON file to display data via .onclick event. I have gotten so far as generating the JSON data and displaying it on screen, but now I want to style it in a table format, where the elements are able to be seen more clearly. Any help would be awesome!
Here's my JS:
addEventListener("load", set_up_click_handler);
function set_up_click_handler() {
var url = 'http://localhost/Advanced_Web/Final_Project/data/exhibitions.json';
var button = document.getElementById("button");
button.addEventListener("click", click_handler);
function click_handler(event) {
var request = new XMLHttpRequest();
request.open('GET', url);
request.addEventListener("load", response_handler);
request.send();
};
function response_handler() {
if (this.status == 200) {
var json = this.responseText;
var data = JSON.parse(json);
window.localStorage.setItem('exhibitions', JSON.stringify(data));
var div = document.createElement("div");
div.setAttribute("id", "dateOfExhibition");
var list = $('<ul/>');
for (var item in data) {
list.append(
$("<li />").text(item + ": " + data[item])
);
}
$('#exhibitions').append(list);
} else {
alert('An error has occurred.');
}
}
}
And if anyone is feeling extra charitable today, I'm also having this following issue: every time I click on my button, the list displays itself once again. How do I rework the code so that it only displays itself once?
without really knowing the style of the table required please see the example formatting the data into a table with the headers on display, the address with an empty array also has not been handled in this function
var jsonData = { "id": "Pavlov's Dog", "dateOfExhibition": "2018-07-08T22:00:00.000Z", "address": [], "street": "Bergmannstrasse 29", "city": "Berlin", "country": "Deutschland", "zip": "10473"};
function createTable(jsonData){
//create headers
var head = $("<tr />");
var keys = Object.keys(jsonData);
keys.forEach(function(key){
head.append($("<th>"+ key + "</th>"));
});
$("#exhibitionTable").append(head);
//append data (if you have multiple objects in an array like this wrap this in a forEach)
var row = $("<tr />");
for (var item in jsonData){
row.append($("<td>"+ jsonData[item] + "</td>"));
}
$("#exhibitionTable").append(row);
}
$(document).ready(function(){
createTable(jsonData);
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table id="exhibitionTable">
</table>
</body>
</html>

Javascript and XML

I am working on JavaScript using HTML5 and I am stuck with a certain aspect. I want to do the following:
Create a table using JavaScript (which is fairly easy)
Extract details from a XML file that is available online
Enter the values in the table
For example, the linkhttp://www.tfl.gov.uk/tfl/syndication/feeds/cycle-hire/livecyclehireupdates.xml contains the information for cycle availability at each station
1. I need to create a table with two columns. One for 'Station Name' and the other for 'No of cycles available'
2. I need to write code that only takes in the above link as input and extracts values of 'Name' and 'nbEmptyDocks'.
Ex : <name> ABC,Surrey </name> <nbEmptyDocks> 10 </nbEmptyDocks>, how will I extract the values ABC,Surrey and 10 and place them in respective columns?
<!DOCTYPE html>
<html>
<body>
<script language= "JavaScript">
document.write('<br> <br><table width="50%" border="1">'); document.write('<th> Dock Station');
document.write('<th> Number of Cycles');
document.write('<br> <br><table width="50%" border="1">');
var Connect = new XMLHttpRequest();
Connect.open("GET", "http://www.tfl.gov.uk/tfl/syndication/feeds/cycle-hire/livecyclehireupdates.xml", false);
Connect.setRequestHeader("Content-Type", "text/xml");
Connect.send(null);
var TheDocument = Connect.responseXML;
var station = TheDocument.childNodes[0];
for (var i = 0; i < 5; i++)
{
var stations = station.children[i];
var name = stations.getElementsByTagName("name");
var avail = Customer.getElementsByTagName("nbEmptyDocks");
document.write("<tr><td>");
document.write( name[0].textContent.toString());
document.write("</td><td>");
document.write(avail[0].textContent.toString());
document.write("</td>");
document.write("</tr>");
}
document.write (" </table>");
</script>
</body></html>
On further reading, I understood that the above code might not work for Chrome, and I need one that works with chrome.
<html>
<body>
<script>
var xmlDoc;
var xmlloaded = false;
function initLibrary()
{
importXML("http:///www.somedomain.com/somesubdir/somefile.xml");
}
function importXML(xmlfile)
{
try
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", xmlfile, false);
}
catch (Exception)
{
var ie = (typeof window.ActiveXObject != 'undefined');
if (ie)
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
while(xmlDoc.readyState != 4) {};
xmlDoc.load(xmlfile);
readXML();
xmlloaded = true;
}
else
{
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.onload = readXML;
xmlDoc.load(xmlfile);
xmlloaded = true;
}
}
if (!xmlloaded)
{
xmlhttp.setRequestHeader('Content-Type', 'text/xml')
xmlhttp.send("");
xmlDoc = xmlhttp.responseXML;
readXML();
xmlloaded = true;
}
}
</script>
</body>
</html>
But this doesnt seem to work either
I would suggest using Google API for grabbing RSS and rending it on your page: you can get started here.
As you say they are not tags themselves, for which it would've been fairly trivial to access them via DOM methods.
Instead, you will need to grab the textContent of the <title> and/or <description> nodes in each <item>. Once you have done that, you will need to do a little string processing. However, the strings are quite predictable, so this is easy:
var text = "Max Temp: 8°C (46°F), Min Temp: 5°C (41°F), Wind Direction: SW, Wind Speed: 8mph, Visibility: good, Pressure: 1002mb, Humidity: 92%, Pollution: n/a, Sunrise: 08:13GMT, Sunset: 16:40GMT";
var pairs = text.split(", "),
info = {};
for (var i=0; i<pairs.length; i++) {
var pair = pairs[i].split(": ");
info[pair[0]] = pair[1];
}
console.log(info)
// {"Max Temp":"8°C (46°F)","Min Temp":"5°C (41°F)","Wind Direction":"SW","Wind Speed":"8mph","Visibility":"good","Pressure":"1002mb","Humidity":"92%","Pollution":"n/a","Sunrise":"08:13GMT","Sunset":"16:40GMT"}
console.log(info["Max Temp"], info["Min Temp"])
// "8°C (46°F)", "5°C (41°F)"

xml parsing from url in javascript

I need some code for parsing XML from a url in javascript. I tried following code:
Source:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html>
<head><title>Employee Data</title>
<script>
// This function loads the XML document from the specified URL, and when
// it is fully loaded, passes that document and the url to the specified
// handler function. This function works with any XML document
function loadXML(url, handler) {
// Use the standard DOM Level 2 technique, if it is supported
if (document.implementation && document.implementation.createDocument) {
// Create a new Document object
var xmldoc = document.implementation.createDocument("", "", null);
// Specify what should happen when it finishes loading
xmldoc.onload = function() { handler(xmldoc, url); }
// And tell it what URL to load
xmldoc.load(url);
}
// Otherwise use Microsoft's proprietary API for Internet Explorer
else if (window.ActiveXObject) {
var xmldoc = new ActiveXObject("Microsoft.XMLDOM"); // Create doc.
xmldoc.onreadystatechange = function() { // Specify onload
if (xmldoc.readyState == 4) handler(xmldoc, url);
}
xmldoc.load(url); // Start loading!
}
}
// This function builds an HTML table of employees from data it reads from
// the XML document it is passed.
function makeTable(xmldoc, url) {
// Create a <table> object and insert it into the document.
var table = document.createElement("table");
table.setAttribute("border", "1");
document.body.appendChild(table);
// Use convenience methods of HTMLTableElement and related interfaces
// to define a table caption and a header that gives a name to each column.
var caption = "Employee Data from " + url;
table.createCaption().appendChild(document.createTextNode(caption));
var header = table.createTHead();
var headerrow = header.insertRow(0);
headerrow.insertCell(0).appendChild(document.createTextNode("Name"));
headerrow.insertCell(1).appendChild(document.createTextNode("Address"));
headerrow.insertCell(2).appendChild(document.createTextNode("State"));
// Now find all <employee> elements in our xmldoc document
var employees = xmldoc.getElementsByTagName("item");
// Loop through these employee elements
for(var i = 0; i < employees.length; i++) {
// For each employee, get name, job, and salary data using standard DOM
// methods. The name comes from an attribute. The other values are
// in Text nodes within <job> and <salary> tags.
var e = employees[i];
var name = e.getAttribute("name");
var job = e.getElementsByTagName("address")[0].firstChild.data;
var salary = e.getElementsByTagName("state")[0].firstChild.data;
alert(name);
// Now that we have the employee data, use methods of the table to
// create a new row and then use the methods of the row to create
// new cells containing the data as text nodes.
var row = table.insertRow(i+1);
row.insertCell(0).appendChild(document.createTextNode(name));
row.insertCell(1).appendChild(document.createTextNode(job));
row.insertCell(2).appendChild(document.createTextNode(salary));
}
}
</script>
</head>
<!--
The body of the document contains no static text; everything is dynamically
generated by the makeTable() function above.
The onload event handler starts things off by calling loadXML() to load the XML data file. Note the use of location.search to encode the name of the xml file in the query string. Load this HTML file with a URL like this: DisplayEmployeeData.html?data.xml
-->
<body onload="loadXML(url, makeTable)">
</body>
</html>

Categories

Resources