First time poster, and still relatively new to javascript... I am trying to figure out how to reflect information from a php file to a canvasjs file.
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "My First Chart in CanvasJS"
},
data: [
{
type: 'line',
dataPoints: [
{ label: "2014/1/2", y: 60, x: 2 },
]
},
{
type: 'line',
dataPoints: [
{ label: "2014/1/2", y: 0, x: 2 },
]
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
Instead of the labels and datapoints etc, I want information from a php file (or how to do it to any type of file) to be collected then displayed into this canvasjs file.
Is there a way to do this?
Sorry if I'm not clear, I really appreciate any help I can get :)
Thanks!
One way would be to make the file you pasted a PHP file, then use PHP in it:
<?php
$dataPoints = [ [ "label" => "2014/1/2", y => 0, x => 2 ] ];
?>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "My First Chart in CanvasJS"
},
data: [
{
type: 'line',
dataPoints: <?php echo json_encode($dataPoints) ?>
},
{
type: 'line',
dataPoints: <?php echo json_encode($dataPoints) ?>
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
Another way would be to create a PHP file that returns the data, and make an AJAX request:
data.php:
<?php
$dataPoints = [ [ "label" => "2014/1/2", y => 0, x => 2 ] ];
echo json_encode($dataPoints);
ui.html:
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script type="text/javascript">
window.onload = function () {
var request = new XMLHttpRequest();
request.onload = function () {
var dataPoints = JSON.parse(request.responseText);
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "My First Chart in CanvasJS"
},
data: [
{
type: 'line',
dataPoints: dataPoints
},
{
type: 'line',
dataPoints: dataPoints
}
]
});
chart.render();
};
request.open('GET', 'data.php', true);
request.send();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
Related
I create a chart using canvasjs. Values display in chart is from mysql database. All working but the problem is, it showing just 1 line on chart (sensors_pres) from table SensorData on chart not all three sensors_pres, sensors_temperature_data and sensors_humidity.
Other problem is on range slider is not showing hour from 0 to 24, test it. Click in left-up on button all and in right-up you will see the number -1 to 96. How can i solve?
I opened data.php file with browser and all values working correct.
Here is my html&javascript code
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.stock.min.js"></script>
<script type="text/javascript">
window.onload = function () {
$.getJSON("data.php", function (result) {
var stockChart = new CanvasJS.StockChart("chartContainer",{
title:{
text:"StockChart with Numeric Axis"
},
animationEnabled: true,
exportEnabled: true,
charts: [{
axisX: {
crosshair: {
enabled: true,
snapToDataPoint: true
}
},
axisY: {
crosshair: {
enabled: true,
//snapToDataPoint: true
}
},
data: [{
type: "line",
dataPoints: result
}]
}],
rangeSelector: {
inputFields: {
startValue: 00,
endValue: 24,
valueFormatString: "###0"
},
buttons: [{
label: "00",
range: 00,
rangeType: "number"
},{
label: "12",
range: 12,
rangeType: "number"
},{
label: "24",
range: 24,
rangeType: "number"
},{
label: "All",
rangeType: "all"
}]
}
});
stockChart.render();
})
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 450px; width: 100%;"></div>
</body>
</html>
here is my php code:
<?php
header('Content-Type: application/json');
$con = mysqli_connect("fdb30.awardspace.net","3758712_lnd","bogdanutzu97","3758712_lnd");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM SensorData");
while($row = mysqli_fetch_array($result))
{
$point = array("label" => $row['reading_time'] , "y" => $row['sensors_pres'],$row['sensors_temperature_data'],$row['sensors_humidity']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
data: [
{
type: "line",
dataPoints: result1
},
{
type: "line",
dataPoints: result2
},
{
type: "line",
dataPoints: result3
}
]
In your data section add 2 more data sets
I am trying to draw CanvasJs chart using data from json file but for some reason it does not work.
The data which I am trying to display are data which is in json file represented as number "####" and value "#"
Please take a look at the code below.
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {
var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Years"
},
axisY: {
title: "Value",
titleFontSize: 24
},
data: [{
type: "column",
yValueFormatString: "# Value",
dataPoints: dataPoints
}]
});
function addData(data) {
for (var i = 0; i < data.length; i++) {
dataPoints.push({
x: new Year(data[i].date),
y: data[i].value
});
}
chart.render();
}
$.getJSON("https://api.worldbank.org/v2/countries/gbr/indicators/UIS.FOSEP.56.F600?format=json", addData);
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
First you need to call the json, $.getJson gives a callback, so once the api gives the data you need to create the dataPoints, once its created create the chart.
I hope the below solution will solve the issue.
Note: If required you can add a loader for the mean time while its loading , so the user will know that some thing is loading
const chartCreation = (data) => {
$("#chartContainer").CanvasJSChart({
animationEnabled: true,
theme: "light2",
title: {
text: "Years"
},
axisY: {
title: "Value",
titleFontSize: 24
},
data: [{
type: "column",
yValueFormatString: "# Value",
dataPoints: dataPoints
}]
});
}
let dataPoints = [];
const addData = (data) => {
dataPoints = data[1].filter(obj => +(obj.date) >= 2010 && +(obj.date) <=2018
).map(obj => ({x: +(obj.date),
y: obj.value ? obj.value : 0}))
// once we have the data pass it to chart creation
// function
chartCreation(dataPoints);
}
$.getJSON("https://api.worldbank.org/v2/countries/gbr/indicators/UIS.FOSEP.56.F600?format=json", (data) =>{
// pass the data to function
addData(data);
});
return{
}
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
Updated
As per the comment, first you can array.filter , once you filter you will get a new array where you can return the properties whatever that you want. using array.map to return what ever the properties.
I'm using Canvasjs to create a candlestick chart. The values are coming from PHP and I use JSON-encode to convert to the javascript array. I recreate the javascript array in the same format as the example, which is this
dataPoints=[{x: new Date(2012,01,01),y:[5198, 5629, 5159, 5385]}]
But the canvas is blank? Here is my code:
<?php
$chart_array[] = array("x"=>"2012-01-01","y"=>array("5198", "5629", "5159", "5385"));
$chart_array[] = array("x"=>"2012-01-02","y"=>array("5366", "5499", "5135", "5295"));
$chart_array = json_encode($chart_array);
?>
<script type="text/javascript">
window.onload = function () {
var resultArray = <?php echo $chart_array; ?>;
var new_array = [];
jQuery.each(resultArray, function(index, item) {
new_array.push({ x: new Date(item.x), y: item.y });
});
console.log(new_array);
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Basic Candle Stick Chart"
},
zoomEnabled: true,
axisY: {
includeZero: false,
title: "Prices",
prefix: "$ "
},
axisX: {
interval: 2,
intervalType: "month",
valueFormatString: "MMM-YY",
},
data: [
{
type: "candlestick",
dataPoints: new_array
}
]
});
chart.render();
}
</script>
console.log show the array exists. Why is a blank canvas showing? How do I solve?
Y-value in your code seems to be string, which should be numeric. Even if you are storing it as string, parsing it to number before passing it to chart-options will work fine.
Here is the working code:
<?php
$chart_array[] = array("x"=>"2012-01-01","y"=>array(5198, 5629, 5159, 5385));
$chart_array[] = array("x"=>"2012-01-02","y"=>array(5366, 5499, 5135, 5295));
$chart_array = json_encode($chart_array);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var resultArray = <?php echo $chart_array; ?>;
var new_array = [];
jQuery.each(resultArray, function(index, item) {
new_array.push({ x: new Date(item.x), y: item.y });
});
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Basic Candle Stick Chart"
},
zoomEnabled: true,
axisY: {
includeZero: false,
title: "Prices",
prefix: "$ "
},
axisX: {
interval: 2,
intervalType: "month",
valueFormatString: "MMM-YY",
},
data: [
{
type: "candlestick",
dataPoints: new_array
}
]
});
chart.render();
}
</script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
Im trying to make a chart that dynamically gets plot values from a .txt file.
Here i can produce a simple chart with canvasjs this is the exact kind of chart i need to make except for it should get x values from a .txt file dynamically.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Percents",
fontFamily: "Impact",
fontWeight: "normal"
},
legend:{
verticalAlign: "bottom",
horizontalAlign: "center"
},
data: [
{
//startAngle: 45,
indexLabelFontSize: 20,
indexLabelFontFamily: "Garamond",
indexLabelFontColor: "darkgrey",
indexLabelLineColor: "darkgrey",
indexLabelPlacement: "outside",
type: "doughnut",
showInLegend: true,
dataPoints: [
{ y: 55, legendText:"55%", indexLabel: "55%" },
{ y: 45, legendText:"45%", indexLabel: "45%" },
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script></head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
Here i try but it fails
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="jquery.canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var dataPoints = [];
//Replace text file's path according to your requirement.
$.get("MYFILE.txt", function(data) {
var x = 0;
var allLines = data.split('\n');
if(allLines.length > 0) {
for(var i=0; i< allLines.length; i++) {
dataPoints.push({x: x , y: parseInt(allLines[i])});
x += .25;
}
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "line",
dataPoints : dataPoints,
}]
});
chart.render();
});
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
It doesnt even give me any errors to debug.
EDIT: Content of .TXT file is very simple
MYFILE.txt
56
As this code, where I only replaced the ajax request by hardcoded data, is working, it has to be a problem with the ajax request itself.
var dataPoints = [];
(function(data) {
var x = 0;
var allLines = data.split('\n');
if(allLines.length > 0) {
for(var i=0; i< allLines.length; i++) {
dataPoints.push({x: x , y: parseInt(allLines[i])});
x += .25;
}
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "line",
dataPoints : dataPoints,
}]
});
chart.render();
})("1\n2\n4\n3");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/jquery.canvasjs.min.js"></script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
As we found out in the comments, it is as I assumed, that you are trying to run the files from the file system via file:/// in your browser, instead of a (local) web server, but ajax requests are not executable in this environment for security reasons.
Im new in Js and Jquery and I have a curiosity about the Jquery Chart that is free to download and I want to make the data inside to be coming from the database to make it dynamic but somehow I find it difficult to loop it in.
here is my sample code, I used PHP to get the database and pass it on a JS variable
<!DOCTYPE HTML>
<html>
<head>
<?php
$link = mysqli_connect("localhost","root","","raksquad_centralized") or die("Error " . mysqli_error($link));
if($link->connect_error){
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM raksquad_centralized.grade";
$result = $link->query($query);
$subject_id= array();
$genAve = array();
while($row = mysqli_fetch_array($result)){
$subject_id[] = $row['subject_id'];
$genAve[]= $row['gen_ave'];
}
?>
<script type="text/javascript">
window.onload = function () {
var DataXAxis = <?php echo json_encode($subject_id); ?>; // X axis that corresponds to students
var DataYAxis = <?php echo json_encode($genAve); ?>; // Y axis that corresponds to grades
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Top Students"
},
animationEnabled: true,
axisY: {
title: "Grades"
},
axisX: {
title: "Students"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "General Average",
dataPoints: [
//the area to loop with the value of DataXAxis, DataYAxis
{y: 98, label: "MT1234" },
{y: 72, label: "MT1236"} //corresponds to the barcharts
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="./canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
appreciate for the help, useful for learning :)
I just use a php code to fetch the data, then json encode it.
On the script use json parse