I want to get data from an url("http://localhost/icx/test/link.html") contains json data. the data contains is like
[{
"call_time": "0",
"total_inc_traffic": "1363.10",
"total_out_traffic": "88.70"
}, {
..............
.............
}]
the json data "total_inc_traffic" is to be shown in the bar chart y axix
<div id="HT_IGW"></div>
<script src="https://cdn.jsdelivr.net/npm/apexcharts#latest"></script>
<script>
var options = {
chart: {
height: 255,
type: 'bar',
},
plotOptions: {
bar: {
horizontal: false,
columnWidth: '55%',
endingShape: 'rounded'
},
},
dataLabels: {
enabled: false
},
stroke: {
show: true,
width: .5,
colors: ['transparent']
},
series: [{
name: 'Traffic In',
data: [
var ourRequest =new XMLHttpRequest();
ourRequest.open('GET','http://localhost/icx/test/link.html');
ourRequest.onload = function(){
var ourData = JSON.parse(ourRequest.responseText);
let result2 = ourData.map(v => Number(v.total_inc_traffic));
console.log(result2);
};
ourRequest.send();
]
}, {
name: 'Traffic Out',
data: [76, 85, 111, 98, 87, 115, 91, 114, 94,76, 85, 111, 98, 87, 115, 91, 114, 94,76, 85, 111,77, 98, 87]
},
],
xaxis: {
categories: ['1', '', '3', '', '5', '', '7', '', '9','','11', '', '13', '', '15', '', '17', '', '19','','21','','23',''],
},
yaxis: {
},
fill: {
opacity: 1
},
tooltip: {
y: {
formatter: function (val) {
return " " + val + " Calls"
}
}
}
}
var chart = new ApexCharts(
document.querySelector("#HT_IGW"),
options
);
chart.render();
</script>
<script>
var ourRequest =new XMLHttpRequest();
ourRequest.open('GET','http://localhost/icx/test/link.html');
ourRequest.onload = function(){
var ourData = JSON.parse(ourRequest.responseText);
let result = ourData.map(v => Number(v.call_time));
console.log(result);
let result2 = ourData.map(v => Number(v.total_inc_traffic));
console.log(result2);
let result3 = ourData.map(v => Number(v.total_out_traffic));
console.log(result3);
};
ourRequest.send();
</script>
</body>
</html>
I expected the output to be shown in the bar graph data, but it gives error data
My error is this
My expectation is
Can anyone help ??
You have an array initializer in a property definition with statements in it:
series: [{
name: 'Traffic In',
data: [
var ourRequest =new XMLHttpRequest();
ourRequest.open('GET','http://localhost/icx/test/link.html');
ourRequest.onload = function(){
var ourData = JSON.parse(ourRequest.responseText);
let result2 = ourData.map(v => Number(v.total_inc_traffic));
console.log(result2);
};
ourRequest.send();
]
You can't do that. With an array initializer ([...]) you can only have expressions in it separated with commas. The expressions are evaluated to create the values to put in the array.
It's not clear to me what you're trying to do there, but that code probably belongs after the big object initializer creating the options object.
You cannot put a code block (the part starting with "var ourRequest") inside array initializer.
If you need the data obtained from ajax call to become the options.series.data property, you need to either create the options object after the ajax call is done, or create the options without that property and add to it when the ajax call is finished.
Anyway if the server that provides the json endpoint is the same as the one that is rendering the page, you should be able to render that information there right when the page is rendered, bypassing need to call any additional ajax request.
As long as you dont want to also call it to update the information without re-rendering the entire page.
Related
i have this code for bar chart but i want to load the data for mysql database
/*
* BAR CHART
* ---------
*/
var bar_data = {
data: [["20-30", 10], ["31-40", 8], ["41-50", 4], ["51-60", 13]],
color: "#3c8dbc"
};
$.plot("#bar-chart", [bar_data], {
grid: {
borderWidth: 1,
borderColor: "#f3f3f3",
tickColor: "#f3f3f3"
},
series: {
bars: {
show: true,
barWidth: 0.5,
align: "center"
}
},
xaxis: {
mode: "categories",
tickLength: 0
}
});
/* END BAR CHART */
There are some hacky ways of using json_encode to output a PHP array in between some <script> tags as one solution.
The better solution though is often to use AJAX to request the data back as JSON and initialize your graph from that. In this way, you are not creating global javascript data variables outside of your javascript.
Hi I have one issue i was creating one HighChart in this Static values to the series data section is working finely. but The same type value from a dynamic section is not showing.
function getusercategorygraph()
{
$.getJSON('config/alumniusermodes.php',function(data){
//alert(json);
//alert($.parseJSON(data));
//alert(obj);
var finaldata = '[';
var tmp = '';
var chart;
$.each(data, function( index, value ) {
finaldata += '{';
$.each(value, function( index, value ) {
//alert(index);
if(index === 'name')
{
tmp = " " + index + " : '" + value + "', ";
}
else
{
tmp = " " + index + " : " + value + ", ";
}
finaldata += tmp;
//alert("finaldata: " + finaldata);
});
finaldata+='},';
});
finaldata +=']';
//alert(finaldata);
chart = new Highcharts.Chart({
chart: {
/* backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 },
stops: [
[0, 'rgb(0, 0, 0)'],
[1, 'rgb(0, 0, 0)']
]
},*/
renderTo : 'user-count',
type: 'column',
},
title: {
text: 'Alumni Users By Category Analytics'
},
xAxis: {
color:'#0077CC',
type: 'category'
},
yAxis: {
title: {
text: 'Total Number of Alumni Members'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y} Members'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y} Members</b><br/>'
},
series: [{
name: "Alumni Type",
colorByPoint: true,
//sdata: [{ name : 'Standard', y : 52, },{ name : 'Silver', y : 24, },{ name : 'Gold', y : 20, },{ name : 'Platinum', y : 6, },]
data: [{ name : 'Standard', y : 52, },{ name : 'Silver', y : 24, },{ name : 'Gold', y : 20, },{ name : 'Platinum', y : 6, },]
//data : finaldata,
}],
});
///chart.series[2].data.push(finaldata);
});
}
i am getting final data like this only
[{ name : 'Standard', y : 52, },{ name : 'Silver', y : 24, },{ name : 'Gold', y : 20, },{ name : 'Platinum', y : 6, },]
but i cant load that in this graph but when paste same value in static mode its showing correctly.
now its showinng a blank section only.
I am new to HighCharts Please help. Thanks in advance.
Your code is creating finaldata as a string, when you want to produce an array. You should have better luck with something like this:
// Create a new array
var finaldata = []
var chart;
// Perform your operations
$.each(data, function( index, value ) {
// Create a new hash
var currentItem = {}
// Create the proper values in your hash
$.each(value, function( index, value ) {
currentItem[index] = value;
});
// Push the new hash to the array
finaldata += currentItem;
});
If all of your data is being passed in a way that your old code successfully created the string you shared, then this should build the object for which you are looking.
To test this you may first want to try leaving your code exactly how it is, and parsing the string to JSON:
// Use this instead of 'data : finaldata'
data: JSON.parse( finaldata ),
This will try to turn your string into the objects on which you are trying to operate. That said, it would be in poor form to practice building an array via string manipulation. I would very strongly encourage you to follow the first approach I detailed.
Hi i Found this as For My Query.
var finaldata = [];
$.getJSON('config/alumniusermodes.php',function(data){
// Create a new array
var finaldata = [];
var chart;
var categories = [];
var tools = [];
$.each(data, function( index, value ) {
var currentItem = {}
finaldata.push({
name: value.name,
y: parseFloat(value.y)
});
});
var chart = new Highcharts.Chart({
chart: {
renderTo : 'user-count',
type: 'column',
},
title: {
text: 'Alumni Users By Category Analytics'
},
xAxis: {
color:'#0077CC',
categories: categories
},
yAxis: {
title: {
text: 'Total Number of Alumni Members'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y} Members'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y} Members</b><br/>'
},
series: [{
name: "Alumni Type",
colorByPoint: true,
data : finaldata,
}],
});
});
This is my right coding which solved my issue
To sort off cap what I'm doing.. I have a loop that creates a table from information pulled from my database. I've setup a superglobal variable inside the loop that assigns one of my table field values to the variable; that part works no problem.
The problem is when I try to call that variable inside the highcharts function, it just doesn't work. The charts don't show up.
$(document).ready(function() {
var $container = $('$global_var');
Highcharts.setOptions({
chart: {
backgroundColor: {
linearGradient: [0, 0, 500, 500],
stops: [
[0, 'rgb(255, 255, 255)'],
[1, 'rgb(240, 240, 255)']
]
},
borderWidth: 2,
plotBackgroundColor: 'rgba(255, 255, 255, .9)',
plotShadow: true,
plotBorderWidth: 1
}
});
var chart1 = new Highcharts.Chart({
chart: {
renderTo: $container,
},
xAxis: {
type: 'datetime'
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
pointStart: Date.UTC(2010, 0, 1),
pointInterval: 3600 * 1000 // one hour
}]
});
});
</script>
In the table that's created, I have a <div> inserted with a dynamic ID (same values as the array I'm attempting to use with the highcharts function), which also works. The only issue is that I can't seem to pass the variable to the renderTo part of the highcharts function.
Here's how I'm declaring my superglobal variable inside my table loop (again, works fine):
$GLOBALS['a'] = $row['Name'] . $temp_array;
TL;DR.. If anyone knows how to pass a variable to renderTo in the Highcharts function I'd really love to know how you do it. Hopefully this is enough info, but if not I'll gladly provide what is requested. Thanks!
In renderTo you need to add string not object as you return.
So it should be
var $container = 'global_var', //id of container, string
and in the chart
chart: {
renderTo: $container,
},
If you would like to combine js variable with string from php variable it should be something like:
var $container = '<?php echo $variable ?>',
This is my first post, apologies if I've asked a question a number of people have already done so. I don't see the answer I need in other posts.
I'm using Flot Charts and have a SQL Server db, I've got a php file that will connect to the db and return all the values within the sql in an array.
<?php
$server = "XXXX";
$database = "XXXX";
$user = "ReportsUser";
$pwd = "ReportsUser";
$cnn = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $pwd);
if(!$cnn)
{
echo "error in connecting";
}
$sql = odbc_exec($cnn, "
SELECT Months
,Referrals
,ProjectedVol
FROM mis.ReferralsBudgetvsActual
WHERE Months <= MONTH(GETDATE())
");
while($result = odbc_fetch_array($sql))
{
$allreferrals[] = array($result['Months'],$result['Referrals'],$result['ProjectedVol']);
}
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
exit;
?>
This works well and produces the array as below
[[1,5981,7465],[2,5473,6962],[3,4974,7391],[4,5731,6985],[5,5891,7080],[6,5168,7136],[7,5551,7543],[8,4427,7242],[9,4617,7204],[10,4807,7642]]
Now, when it all comes together in the jquery file, this is where I end up getting stuck. I don't see where it pulls any other columns back apart from the first data column, how can this be done?
// document ready function
$(document).ready(function() {
var chartColours = ['#88bbc8', '#ed7a53', '#9FC569', '#bbdce3', '#9a3b1b', '#5a8022', '#2c7282'];
// function for refreshing shiftstats chart
make_chart();
function make_chart() {
$.ajax({
cache: 'false',
type: 'GET',
dataType: 'json',
url: "test.php",
success: function(data) {
var d1 = data;
var d2 = data;
//define placeholder class
var placeholder = $(".shifts-chart");
//graph options
var options = {
grid: {
show: true,
aboveData: true,
color: "#3f3f3f" ,
labelMargin: 5,
axisMargin: 0,
borderWidth: 0,
borderColor:null,
minBorderMargin: 5 ,
clickable: true,
hoverable: true,
autoHighlight: true,
mouseActiveRadius: 20
},
series: {
grow: {
active: false,
stepMode: "linear",
steps: 50,
stepDelay: true
},
lines: {
show: true,
fill: false,
lineWidth: 4,
steps: false
},
points: {
show:true,
radius: 5,
symbol: "circle",
fill: true,
borderColor: "#fff"
}
},
legend: {
position: "ne",
margin: [0,-25],
noColumns: 0,
labelBoxBorderColor: null,
labelFormatter: function(label, series) {
// just add some space to labes
return label+' ';
}
},
yaxis: { min: 0 },
xaxis: {ticks:11, tickDecimals: 0},
colors: chartColours,
shadowSize:1,
tooltip: true, //activate tooltip
tooltipOpts: {
content: "%s : %y.0",
shifts: {
x: -30,
y: -50
}
}
};
$.plot(placeholder,
[{
label: "Referrals",
data: d1,
lines: {fillColor: "#f2f7f9"},
points: {fillColor: "#88bbc8"}
},
{
label: "ProjectedVol",
data: d2,
lines: {fillColor: "#f2f7f9"},
points: {fillColor: "#88bbc8"}
}
], options);
}
});
}
});
Thanks
You'll need to change your php array creation to properly format the data into two series:
$d1 = array();
$d2 = array();
while($result = odbc_fetch_array($sql))
{
array_push($d1, array($result['Months'], $result['Referrals']));
array_push($d2, array($result['Months'], $result['ProjectedVol']));
}
$allreferrals = array($d1, $d2);
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
This should return it as an array of arrays:
[
[[1,5981],[2,5473],[3,4974],[4,5731],[5,5891],[6,5168],[7,5551],[8,4427],[9,4617,7204],[10,4807]],
[[1,7465],[2,6962],[3,7391],[4,6985],[5,7080],[6,7136],[7,7543],[8,7242],[9,7204],[10,7642]]
]
(Hopefully I have the syntax correct, I'm not a fan of php)
Update from comment
If you are returning a slew of series, you might be better returning an associative array from PHP:
$allreferrals = array('ref' => array(), 'projVol'=> array());
while($result = odbc_fetch_array($sql))
{
array_push($allreferrals['ref'], array($result['Months'], $result['Referrals']));
array_push($allreferrals['projVol'], array($result['Months'], $result['ProjectedVol']));
}
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
Then back in the javascript:
$.plot(placeholder,
[{
label: "Referrals",
data: data["ref"]
},
{
label: "ProjectedVol",
data: data["projVol"]
}],
options);
I had a highcharts temperature gauge working when I put the javascript inline in my php file. However, I wanted to put the highcharts code in an "included" js file. Before, when I coded the javascript inline with the php file, it looked something like this:
// html and php above
// this inline code below works
<script>
$(document).ready(function(){
// here i simply accessed a php variable from
var $temperature_F = <?php echo round((($temp["Temperature"] * 9) / 5) + 32, 1); ?>;
var chart1 = new Highcharts.Chart({
// code initializing everything else in the highchart
series: [{
data: [{
id: 'temperature',
y: $temperature_F, // value taken from php variable
tooltip: {
valueSuffix: ' \xB0F'
}
}]
}]
});
})
</script>
// html and php below
Now, all I did was take this chunk of code, put it in a .js file and "include" it. I now just call a Print function from the php file, defined in my .js file, passing it the php variables I need. Like this:
<script type="text/javascript">
PrintTemperatureChart(1, '<?php echo $temperatureToDisplay; ?>', '<?php echo $dewPointToDisplay; ?>', '<?php echo $relativeHumidityToDisplay; ?>');
</script>
From within this function, I am able to "alert" out the expected php variables that I passed in, however, when I attempt to set "data:" to one of these variables, it breaks the chart. When I replace the variable with a dummy hard-coded value, it works. So I know just about everything else is set up correctly. Here's the function in the .js file:
function PrintTemperatureChart(unitsMode, temperature, dewPoint, relativeHumidity){
alert(unitsMode + ", " + temperature + ", " + dewPoint + ", " + relativeHumidity);
$(function () {
alert("The passed temperature = " + temperature);
var $theTemp = temperature;
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'Temperature_Chart',
type: 'gauge',
margin: 0
},
title: {
text: 'Temperature'
},
pane: {
startAngle: -150,
endAngle: 150,
background: [{
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, '#FFF'],
[1, '#333']
]
},
borderWidth: 0,
outerRadius: '109%'
}, {
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, '#333'],
[1, '#FFF']
]
},
borderWidth: 1,
outerRadius: '107%'
}, {
// default background
}, {
backgroundColor: '#DDD',
borderWidth: 0,
outerRadius: '105%',
innerRadius: '103%'
}]
},
yAxis: {
title: {
text: '\xB0F'
},
min: 0,
max: 120,
minorTickInterval: 1,
minorTickWidth: 1,
minorTickLength: 5,
minorTickPosition: 'inside',
minorGridLineWidth: 0,
minorTickColor: 'black',
tickInterval: 10,
tickWidth: 2,
tickPosition: 'inside',
tickLength: 10,
tickColor: 'black',
},
series: [{
name: 'Temperature',
data: [$theTemp], // this doesn't work
// this is the js var set to the passed in temperature
// I've also just tried using the param directly
// only a hard coded value will work
// i.e. data: [56],
tooltip: {
valueSuffix: ' \xB0F'
}
}]
});
});
}
I just need to use these variables passed in as data in my chart. Thanks in advance!
By placing single quotes around the PHP code like this:
PrintTemperatureChart(1, '<?php echo $temperatureToDisplay; ?>');
these variables were being passed as strings, which is incompatible with the integer type the "data" field expects in HighCharts. Solution:
PrintTemperatureChart(1, <?php echo $temperatureToDisplay; ?>);