Can't get rid of XML in "variables" - javascript

This is involving Intuit's Quickbase. I am trying to use Highcharts.JS and have the data loaded via XML into the graph. The problem I am currently having is that in the variables I have two variables that do not need to be on the graph that relate to something else entirely.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>CoT</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://code.highcharts.com/highcharts.js"></script>
<!-- JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Components Over Time'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Units'
}
},
series: []
};
// Load the data from the XML file
$.get('https://dbname.quickbase.com/db/?apptoken=&act=API_DoQuery&query=%7B14.EX.%27_FID_9%7D&clist=7.24.25.26.27.28.29.30.31.32.33.34.35.36.37', function(xml) {
// Split the lines
var $xml = $(xml);
// push categories
$xml.find('variables').each(function(i, variables) {
options.xAxis.categories.push($(variables).text());
});
// push series
$xml.find('record').each(function(i, record) {
var seriesOptions = {
name: $(record).find('methane').text(),
data: [],
};
// push data points
$(record).find('methane').each(function(i, point) {
seriesOptions.data.push(
parseInt($(point).text())
);
});
// add it to the options
options.series.push(seriesOptions);
});
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="container" style="width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
The following has also been tried in the push categories to no success
$xml.find('variables:not(iol):not(__iol)').each(function(i, variables) {
options.xAxis.categories.push($(variables).text());
});
Both cause the graph to come back looking like ( http://i.imgur.com/fb8A2uO.jpg )
Edit: This is the XML output
<?xml version="1.0" ?>
<qdbapi>
<action>API_DoQuery</action>
<errcode>0</errcode>
<errtext>No error</errtext>
<dbinfo>
<name>RESULT</name>
<desc></desc>
</dbinfo>
<variables>
<__iol>&rand='+new Date().getTime())};"></__iol>
<iol><img qbu='module' src='/i/clear2x2.gif' onload="javascript:if(typeof QBU=='undefined'){QBU={};$.getScript(gReqAppDBID+'?a=dbpage&pagename=</iol>
</variables>
<chdbids>
</chdbids>
<record>
<sample_date>1386892800000</sample_date>
<hydrogen>0.002</hydrogen>
<helium>0.114</helium>
<oxygen/>
<hydrogen_sulfide/>
<nitrogen>1.926</nitrogen>
<co2>0.454</co2>
<methane>82.163</methane>
<ethane>6.353</ethane>
<propane>4.760</propane>
<iso_butane>0.618</iso_butane>
<n_butane>1.819</n_butane>
<iso_pentane>0.491</iso_pentane>
<n_pentane>0.544</n_pentane>
<hexanes_>0.756</hexanes_>
<update_id>1408654196361</update_id>
</record>
<record>
<sample_date>1383782400000</sample_date>
<hydrogen>0.006</hydrogen>
<helium>0.038</helium>
<oxygen/>
<hydrogen_sulfide/>
<nitrogen>0.512</nitrogen>
<co2>0.844</co2>
<methane>83.178</methane>
<ethane>8.678</ethane>
<propane>3.631</propane>
<iso_butane>0.493</iso_butane>
<n_butane>1.097</n_butane>
<iso_pentane>0.342</iso_pentane>
<n_pentane>0.371</n_pentane>
<hexanes_>0.810</hexanes_>
<update_id>1408981434690</update_id>
</record>
<record>
<sample_date>1369699200000</sample_date>
<hydrogen>0.004</hydrogen>
<helium>0.060</helium>
<oxygen/>
<hydrogen_sulfide/>
<nitrogen>1.684</nitrogen>
<co2>0.443</co2>
<methane>77.742</methane>
<ethane>10.430</ethane>
<propane>6.842</propane>
<iso_butane>0.587</iso_butane>
<n_butane>1.482</n_butane>
<iso_pentane>0.232</iso_pentane>
<n_pentane>0.249</n_pentane>
<hexanes_>0.245</hexanes_>
<update_id>1408981112624</update_id>
</record>
</qdbapi>

Try
// note the space character between tags ,
// to prevent rendering `<variables />` within xml
$xml.find("variables").replaceWith("<variables> </variables>");
http://jsfiddle.net/xwzox6rg/

Related

Run a script only after another one completes

I have multiple scripts in my HTML header. the two of concern are as follows:
1) JS script ('Infected Data') produces an object with data. The data is retrieved and computed from a google scripts file, so naturally it takes a bit.
2) A script which generates a map. The map is color coded depending on the values of the Infected Object Data.
The problem is the map loads before i can get the object, so it is not colored.
Map should look like this:
Map looks like this:
HTML Header:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>JQVMap - World Map</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<link href="../dist/jqvmap.css" media="screen" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="../dist/jquery.vmap.js"></script>
<script type="text/javascript" src="../dist/maps/jquery.vmap.world.js" charset="utf-8"></script>
<script type="text/javascript" src="js/jquery.vmap.sampledata.deaths.js"></script>
<script type="text/javascript" src="js/jquery.vmap.sampledata.infected.js"></script>
<script>
jQuery(document).ready(function () {
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#333333',
color: '#ffffff',
hoverOpacity: 0.8,
selectedColor: '#3498DB',
enableZoom: true,
showTooltip: true,
scaleColors: ['#F3A291', '#FF4F3B'],
values: infected_data,
normalizeFunction: 'polynomial',
onLabelShow: function(event, label, code)
{
// Remove for Russian Joke
/*if (code == 'ru')
{
// Plain TEXT labels
label.text('Bears, vodka, balalaika');
}
else*/
label.html('<div class="map-tooltip"><h1 class="header">'+label.html()+'</h1><p class="description">Infected: '+infected_data[code]+'</p><p class="description">Deaths: '+death_data[code]+'</p></div>');
/*else if (code == 'us')
{
label.html(label.html()+' (GDP - '+sample_data[code]+')');
}*/
},
/*onRegionOver: function(event, code)
{
if (code == 'ca')
{
event.preventDefault();
}
}, */
});
});
</script>
</head>
Infected Data JS FIle:
var infected_dataINT = {};
var infected_data = {};
const url = "https://script.google.com/macros/s/AKfycbzsyQNJwDvQc5SvNGEDZZOoNI3XxNar9PA9sRucZx7mgzfWpFQ/exec";
// Declare an async function
const getData = async () => {
// Use the await keyword to let JS know this variable has some latency so it should wait for it to be filled
// When the variable is fetched, use the .then() callback to carry on
const DataJSON = await fetch(url).then(response =>
response.json()
)
return await DataJSON
};
console.log(getData());
getData().then(result => {
console.log(result);
infected_dataINT = result;
console.log(infected_dataINT);
function toString(o) {
Object.keys(o).forEach(k => {
if (typeof o[k] === 'object') {
return toString(o[k]);
}
o[k] = '' + o[k];
});
return o;
}
console.log(toString(infected_dataINT));
infected_data = toString(infected_dataINT);
})
How can i slow down the jQuery(document).ready(function () {.... to run only after <script type="text/javascript" src="js/jquery.vmap.sampledata.infected.js"></script> has ran
You can dynamically append the script element to the document after the response has been recieved from the server like this:
let script = document.createElement('script');
script.src = 'myJqueryFile.js';
document.head.appendChild(script);
You just have to put those jquery codes inside a .js file.
Sounds like an asynch problem...
Where do you close the header?
</head>
And where is your onload event to synchrinise things?
<body onload="Function_That_KickStarts_Everything();">
Please use the correct document structure and ensure everything begins with the ONLOAD event so that 3rd party libraries may all load and synchronize... follow this please:
<html>
<head>
<style type="text/css">
</style>
</head>
<body onload="Function_That_KickStarts_Everything();">
<script src="Third_Party_Library_1.js"></script>
<script src="Third_Party_Library_2.js"></script>
<script type="text/javascript">
</script>
</body>
</html>

Make bar chart using canvas.js

Hello I am new to JavaScript but having difficulty with the generation of charts using the canvas.js library. The step that I am failing to replicate is the example on canvasjs website https://canvasjs.com/docs/charts/how-to/create-charts-from-csv/ for generating a chart using a csv document. Will I have to approach differently since I am hosting from google sheets?
My current code is:
<!DOCTYPE html>
<html>
<head>
<title>TEst</title>
<script type="text/javascript">
window.onload = function(){
var dataPoints = [];
function getDataPointsFromCSV(csv) {
var dataPoints = csvLines = points = [];
csvLines = csv.split(/[\r?\n|\r|\n]+/);
for (var i = 0; i < csvLines.length; i++)
if (csvLines[i].length > 0) {
points = csvLines[i].split(",");
dataPoints.push({
x: parseFloat(points[0]),
y: parseFloat(points[1])
});
}
return dataPoints;
}
//Replace text file's path according to your requirement.
$.get("https://docs.google.com/spreadsheets/d/12o9ekzln8KB3Uyg2fVou6UtIUlrC5GC973Ttk6GsjKs/edit?usp=sharing",function(data) {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Chart from CSV",
},
data: [{
type: "line",
dataPoints: getDataPointsFromCSV(data)
}]
});
chart.render();
});
}
</script>
</head>
<body>
<p>it worked:</p>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
When I inspect with chrome I get the following error.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Hello there is already a good answer to this question, I added a link to the bottom of this answer.
It sounds like Google is not allowing you to load the data from their website.
Try replacing your dataPoints: getDataPointsFromCSV(data) with some example data from chart.js's site to make sure the rest of your code is working.
No 'Access-Control-Allow-Origin' header is present on the requested resource. with github sites

canvasjs live updating data from database

I am new to web based visualization tool I used chartjs before but I did not find any solution for chartjs so, I transferred to canvasjs.Now I'm done creating the chart and it is successfully shown, thus I want to make it moving without refreshing because the data from the database is constantly moving. Here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
window.onload = function () {
$.getJSON("json.php", function(result){
var dps= [];
//Insert Array Assignment function here
for(var i=0; i<result.length;i++) {
dps.push({"label":result[i].ts, "y":result[i].ph});
}
//Insert Chart-making function here
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled:true,
panEnabled:true,
animationEnabled:true,
title:{
text: "myChart from mySQL database"
},
axisX:{
title: "TimeStamp"
},
axisY:{
title: "myDataPoints",
minimum: 0
},
data: [{
type: "spline",
dataPoints:
dps
}]
});
chart.render();
});
}
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
now, I would like to ask for help out there What do I need to keep this chart moving...??
If you want the lines to move, you need to remove dataPoints from the beginning of the array. You can do so using shift function in JS.
for(var i=0; i<result.length;i++) {
dps.push({"label":result[i].ts, "y":result[i].ph});
dps.shift();
}
This would do the trick for you.

HTML file won't generate anything on webpage using Chart.js

I'm trying to build a basic chart using the Chart.js JavaScript framework. I believe I have everything completely the way it should be given an example I've been following, however it will not generate the chart (or anything) in any browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ChartJS Analytic</title>
<script id="src/chart.js"></script>
</head>
<body>
<div id="center"><canvas id="lineChart"></canvas></div>
<script>
var lineChartData = {
labels : ["2010","2011","2012","2013"],
datasets : [{
data : [150,200,250,150]
}, {
data : [200,170,150,200]
}]
};
var lineChart = document.getElementById('lineChart').getContext('2d');
new Chart(lineChart).Line(lineChartData);
</script>
</body>
</html>
I am using WebStorm and no errors or warnings are detected. Can anyone tell me what the issue is here?
The problem lied in the line with new Chart(lineChart)...
This is incorrectly referenced in modern Chart.js. That line should look like this:
var myLineChart = Chart.Line(lineChart, {
data: lineChartData,
options: lineOptions
});

google visualization datatable not going to csv

Been messing around with this on google playground, and it appears to work without any errors. However when I go to do the export options it doesn't give me anything. Any idea?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['table']});
</script>
<script type="text/javascript">
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Name', 'Height', 'Smokes'],
['Tong Ning mu', 174, true],
['Huang Ang fa', 523, false],
['Teng nu', 86, true]
]);
var options = { 'showRowNumber': true };
options['page'] = 'enable';
options['pageSize'] = 3;
options['pagingSymbols'] = { prev: 'prev', next: 'next' };
options['pagingButtonsConfiguration'] = 'auto';
var components = [
{ type: 'html', datasource: data },
{ type: 'csv', datasource: data }
];
var container = document.getElementById('toolbar_div');
google.visualization.drawToolbar(container, components);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, options);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="table"></div>
<dov id="toolbar_div"></div>
</body>
</html>
​
According to the documentation you have to pass the data through a URL and not any hand-populated data objects. See:
https://developers.google.com/chart/interactive/docs/gallery/toolbar
Usage
To use a toolbar, your visualization must get its data from a URL; you cannot pass in hand-populated DataTable or DataView objects. You will pass the URL of the data used to populate your visualization into the drawToolbar() method.
Code:
$('#Export').click(function () {
var csvFormattedDataTable = google.visualization.dataTableToCsv(data);
var encodedUri = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvFormattedDataTable);
this.href = encodedUri;
this.download = 'table-data.csv';
this.target = '_blank';
});
Explanation:
Check my answer posted here for an explanation of the code. Export is the Id of the anchor element on the page with the download option.

Categories

Resources