Not able to find the id in javascript - javascript

I'm trying to plot a graph inside a div which is dynamically created. A string of HTML divs is passed from the backend and then it is appended to the comparison_widgets div. Then a call to a function is made which needs to plot a graph(Highcharts) inside that div.
But when it goes to the function it says
Error: Syntax error, unrecognized expression: #id_Asia/Pacific_NorthAmerica
throw new Error( "Syntax error, unrecognized expression: " + msg );
It is not able to find the id, i guess. Where I'm going wrong?
Here result[1] is the div string, ie
<div id="widget_Asia/Pacific_NorthAmerica" class="portlet ui-widget ui-widget-content ui-helper-clearfix ui-corner-all">
<div class="portlet-header ui-corner-all">
<span class="close right">x</span>
Asia / Pacific_North America
</div>
<div id="id_Asia/Pacific_NorthAmerica" class="portlet-content"></div>
</div>
result[2] is id_Asia/Pacific_NorthAmerica
and result[0] is the data that needs to be plotted on the graph.
The AJAX FUNCtion
$.ajax({
dataType : "json",
type: "POST",
url: "/dashboard/",
data : { 'comparison_widget_id' : comparison_widget_id,'level_id':level_id, },
success: function(result){
$("#comparison_widgets").append(result[1]);
var div_id = "id_"+result[2];
comparison_chart(div_id,result[0]);
}
});
function comparison_chart(div_id,result) {
var MAXPOINTS = 20;
var level_number = 0;
Highcharts.setOptions({
global: {
useUTC: false,
}
});
$("#"+div_id).highcharts({
chart: {
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
if(series.data.length > MAXPOINTS){
series.addPoint([x, y], true, true);
}
else{
series.addPoint([x, y], true, false);
}
},5000);
},
}
},
title: {
text: 'Energy Chart'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
}
},
tooltip: {
formatter: function() {
var s;
s = this.y + 'kWh';
return s;
}
},
series: [{
type: 'spline',
name: 'Live Data',
data: result[0],
showInLegend: true,
}, {
type: 'pie',
data: result[2],
center: [90, 20],
size: 125,
cursor: 'pointer',
showInLegend: true,
dataLabels: {
enabled: false,
},
point :{
events:{
click : function(){
level_number = level_number + 1;
$.ajax({
dataType: "json",
type : 'POST',
url : '/dashboard/',
data : {'name': this.name, 'level_number' : level_number},
success: function(result){
comparison_chart(result);
}
});
}
}
},
}]
});
}

Use $('#widget_Asia\\/Pacific_NorthAmerica')

Related

Highcharts Not displaying function's data values

i Have created a Highchart using the Following Highchart's Demo:
https://www.highcharts.com/demo/dynamic-update
Now What I did I created my Own function to add dynamic values to the Chart.
I created a function to get the dynamic data from a particular php file whose data changes on every page load event.
I am getting the data values in the getData function console.log
Here is the Script That I am using.
<script type="text/javascript">
$(document).ready(function(){
function getData(){
$.ajax({
type: 'GET',
url: 'data.php',
success: function(data){
// var number = document.write(data) ;
console.log(data);
return data ;
}
}) ;
}
Highcharts.chart('chart', {
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = getData();
console.log(y);
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
time: {
useUTC: false
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
headerFormat: '<b>{series.name}</b><br/>',
pointFormat: '{point.x:%Y-%m-%d %H:%M:%S}<br/>{point.y:.2f}'
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: getData()
});
}
return data;
}())
}]
});
});
</script>
Now as you can see that I have created a getData function and getting the data value in return.
On console log under the getData function, I am getting integer Value in return every one second.
the problem is that under the Highchart's function, I am not able to get the data values using getData function, it's returning undefined in the console .
Highchart's is running but it does not show any data points. it is moving but without showing any data points.
Please correct me in the area , where I am doing wrong.
Any help is appreciated. Thanks
ajax calls are run asynchronously so you cant really return data from it.
instead you should render chart inside the ajax success function.
A good example is here already.
https://www.highcharts.com/docs/working-with-data/live-data
Basically
1. point on load to call a function getData
2. in Getdata call ajax function.
3. in success of ajax render chart with new data.
document.addEventListener('DOMContentLoaded', function() {
chart = Highcharts.chart('container', {
chart: {
type: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
/**
* Request data from the server, add it to the graph and set a timeout
* to request again
*/
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second - add this if you want to auto refresh
// setTimeout(requestData, 1000);
},
cache: false
});
}

Highcharts maps with decimals

I try to replicate this example file of highcharts with a different kind of data file. In the new database, life expectancy per country is 13 decimal places. The source is also world bank, which makes the structure comparable. Here is the example JSFIDDLE. Unfortunately, this does not work because presumably "numRegex = /^[0-9.]+$/" on line 26 is wrong. Unfortunately I have no idea what should be put here.
HTML
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/maps/modules/map.js"></script>
<script src="https://code.highcharts.com/mapdata/custom/world.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css">
<!-- Flag sprites service provided by Martijn Lafeber, https://github.com/lafeber/world-flags-sprite/blob/master/LICENSE -->
<link rel="stylesheet" type="text/css" href="//github.com/downloads/lafeber/world-flags-sprite/flags32.css" />
<div class="container_fluid">
<div class="row">
<div class="col-lg-12 col-md-12">
<div class="panel color-orange shadow">
<div class="panel-heading text-white text-center">
</div>
<div class="panel-body color-grey text-center">
<div class="col-lg-12 col-md-12 position-padding-ver position-padding-hor">
<div id="wrapper_landkaart">
<div id="container"></div>
<div id="info">
<span class="f32"><span id="flag"></span></span>
<h2></h2>
<div class="subheader">Click countries to view history</div>
<div id="country-chart"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
JavaScript
$.ajax({
url: 'https://cdn.filestackcontent.com/WZkkd6c4S3euwmgoV88v',
success: function(csv) {
// Parse the CSV Data
/*Highcharts.data({
csv: data,
switchRowsAndColumns: true,
parsed: function () {
console.log(this.columns);
}
});*/
// Very simple and case-specific CSV string splitting
function CSVtoArray(text) {
return text.replace(/^"/, '')
.replace(/",$/, '')
.split('","');
}
csv = csv.split(/\n/);
var countries = {},
mapChart,
countryChart,
numRegex = /^[0-9\.]+$/,
lastCommaRegex = /,\s$/,
quoteRegex = /\"/g,
categories = CSVtoArray(csv[2]).slice(4);
// Parse the CSV into arrays, one array each country
$.each(csv.slice(3), function(j, line) {
var row = CSVtoArray(line),
data = row.slice(4);
$.each(data, function(i, val) {
val = val.replace(quoteRegex, '');
if (numRegex.test(val)) {
val = parseInt(val, 10);
} else if (!val || lastCommaRegex.test(val)) {
val = null;
}
data[i] = val;
});
countries[row[1]] = {
name: row[0],
code3: row[1],
data: data
};
});
// For each country, use the latest value for current population
var data = [];
for (var code3 in countries) {
if (countries.hasOwnProperty(code3)) {
var value = null,
year,
itemData = countries[code3].data,
i = itemData.length;
while (i--) {
if (typeof itemData[i] === 'number') {
value = itemData[i];
year = categories[i];
break;
}
}
data.push({
name: countries[code3].name,
code3: code3,
value: value,
year: year
});
}
}
// Add lower case codes to the data set for inclusion in the tooltip.pointFormat
var mapData = Highcharts.geojson(Highcharts.maps['custom/world']);
$.each(mapData, function() {
this.id = this.properties['hc-key']; // for Chart.get()
this.flag = this.id.replace('UK', 'GB').toLowerCase();
});
// Wrap point.select to get to the total selected points
Highcharts.wrap(Highcharts.Point.prototype, 'select', function(proceed) {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
var points = mapChart.getSelectedPoints();
if (points.length) {
if (points.length === 1) {
$('#info #flag').attr('class', 'flag ' + points[0].flag);
$('#info h2').html(points[0].name);
} else {
$('#info #flag').attr('class', 'flag');
$('#info h2').html('Comparing countries');
}
$('#info .subheader').html('<h4>Historical population</h4><small><em>Shift + Click on map to compare countries</em></small>');
if (!countryChart) {
countryChart = Highcharts.chart('country-chart', {
chart: {
height: 250,
spacingLeft: 0
},
credits: {
enabled: false
},
title: {
text: null
},
subtitle: {
text: null
},
xAxis: {
tickPixelInterval: 50,
crosshair: true
},
yAxis: {
title: null,
opposite: true
},
tooltip: {
split: true
},
plotOptions: {
area: {
color: '#fa7921'
},
series: {
animation: {
duration: 500
},
marker: {
enabled: false
},
threshold: 0,
pointStart: parseInt(categories[0], 10)
}
}
});
}
$.each(points, function(i) {
// Update
if (countryChart.series[i]) {
/*$.each(countries[this.code3].data, function (pointI, value) {
countryChart.series[i].points[pointI].update(value, false);
});*/
countryChart.series[i].update({
name: this.name,
data: countries[this.code3].data,
type: points.length > 1 ? 'line' : 'area'
}, false);
} else {
countryChart.addSeries({
name: this.name,
data: countries[this.code3].data,
type: points.length > 1 ? 'line' : 'area'
}, false);
}
});
while (countryChart.series.length > points.length) {
countryChart.series[countryChart.series.length - 1].remove(false);
}
countryChart.redraw();
} else {
$('#info #flag').attr('class', '');
$('#info h2').html('');
$('#info .subheader').html('');
if (countryChart) {
countryChart = countryChart.destroy();
}
}
});
// Initiate the map chart
mapChart = Highcharts.mapChart('container', {
title: {
text: 'Population history by country'
},
subtitle: {
text: 'Source: The World Bank'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
colorAxis: {
type: 'logarithmic',
endOnTick: false,
startOnTick: false,
minColor: '#9E90B3',
maxColor: '#3D1C5C',
min: 50000
},
tooltip: {
footerFormat: '<span style="font-size: 10px">(Click for details)</span>'
},
series: [{
data: data,
mapData: mapData,
joinBy: ['iso-a3', 'code3'],
name: 'Current population',
allowPointSelect: true,
cursor: 'pointer',
states: {
select: {
color: '#D06918',
borderColor: 'black',
dashStyle: 'shortdot'
}
}
}]
});
// Pre-select a country
mapChart.get('us').select();
}
});
Hopefully someone can help me further on this. Thank you very much.
Your CSV file is broken it looks like this:
"Data Source,""World Development Indicators"","
it should look like
"Data Source","World Development Indicators",
CSV won't split on a , if it's in quotes hence you can include comma's in your file as text if you include them in quotes.
Fix your CSV file and it should work.

Have an issue with JavaScript, AJAX code displaying data

I need some tips from you out there to come over a good solution on my problem with JavaScript, AJAX and JSON data. I want to fill a generic set with barcharts (I am using HighCharts) on my web page. The data is in JSON format which from the start I only used date and value as pair data set. The solution works fine of I had only one bar chart it, but I have a lot of charts on my page and I need to show all of them (up to twelve).
Now I want to adjust for displaying more than one graph. In the code below the DataMacro array works fine with the chart. It also has a hard coded ID matching a . Now I have a series of in the page like id=barchart11, id=barchar21, and so on. In the dataset I have made a tag called PanelCodeUI that I am going to use looping through the dataset. The problem is how to do that. The each-loop will now fill in all date,value for all vessels.
And further it I need to restructure the function which is displaying the barchart. The best thing would be to call a function with a data array and panelCodeUI id just replacing the name of the barchart and set in the datamacro as is. But I don’t know how to do this. The data is mixed between all vessels and I need to collect all data before sending to a function. So is the problem with AJAX and JavaScript with is asynchron. I need to ensure that it behaves correctly and fast.
Maybe I need to change my dataset, or I need to do this in several step like finding all vessel IDs then do another AJAX call to get date,value pair from a vessel and then displaying. I hope there is a way to do this with this data set and hope somebody can help me on this
Here is a bit of the JSON data set:
[
{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465084800000,"Value":844,"VesselId":1,"SectorId":2,"PanelCodeUI":"21","VesselCodeUI":"21","VesselSorting":1},
{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465084800000,"Value":8720,"VesselId":4,"SectorId":1,"PanelCodeUI":"11","VesselCodeUI":"12","VesselSorting":2},
{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465084800000,"Value":948,"VesselId":5,"SectorId":1,"PanelCodeUI":"11","VesselCodeUI":"11","VesselSorting":1},
{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465084800000,"Value":0,"VesselId":6,"SectorId":3,"PanelCodeUI":"31","VesselCodeUI":"31","VesselSorting":1},
{"__type":"Demo.Entities.OilProductionLast5DaysEntity","Date":1465171200000,"Value":2067,"VesselId":1,"SectorId":2,"PanelCodeUI":"21","VesselCodeUI":"21","VesselSorting":1}
]
And here is the JavaScript code so far:
$(function () {
var datamacro = [];
$.ajax({
type: "POST",
url: '../Services/HighChartService.asmx/GetOilProductionLast5DaysByActiveVessels',
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (seriedata) {
console.log(JSON.stringify(seriedata.d));
var productions = seriedata.d;
$.each(productions, function (index, productions) {
var yval = productions.Value;
var xval = productions.Date;
var x = [xval, yval];
datamacro.push(x);
//alert("productions Name: " + productions.Date + "\nID: " + productions.Value);
});
$(function () {
//var bchart = '#barchart' + vesselindex.toString();
// want this to be looped with generic names like #barchart11, #barchart21, #barchart31 and so on
$('#barchart11').highcharts({
chart: {
type: 'column'
},
title: {
text: 'LAST FIVE DAYS'
},
subtitle: {
text: ''
},
xAxis: {
type: "datetime",
tickInterval: 24 * 3600 * 1000,
labels: {
rotation: -45,
align: 'right'
},
dateTimeLabelFormats: { // don't display the dummy year
day: '%e. %b',
},
//crosshair: true
},
credits: {
enabled: false
},
yAxis: {
labels: {
enabled: false
},
title: {
text: null
}
},
tooltip: {
formatter: function () {
return Highcharts.dateFormat('%d/%m/%Y', new Date(this.x)) + '<br/>' + ' in barrels: ' + this.y;
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}, series: {
pointRange: 24 * 3600 * 1000, // one day
pointInterval: 3600 * 1000
}
},
series: [{
//name: '',
showInLegend: false,
data: datamacro,
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
format: '{point.y:.1f}', // one decimal
y: 10, // 10 pixels down from the top
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
}]
});
});
},
error: function (r) {
alert(r.responseText);
},
failure: function (r) {
alert(r.responseText);
}
});
});
If i understand correctly, you would like to draw a chart for each different panelCodeUI ?
If that's the case, change your code after AJAX success with that :
var productions = seriedata.d;
var listPanelCodeUI = productions.map(function(p){return p.PanelCodeUI}).filter(function(item, pos, self) {
return self.indexOf(item) == pos;
});
//listPanelCodeUI : [21,11,31]
listPanelCodeUI.sort();
listPanelCodeUI.forEach(function(e){
datamacro = [];
//Create a div for each panelCodeUI
$("body").append("<div id='barchart" + e + "'></div>");
var divId = "#barchart"+e;
//Filter productions for specific panelCodeUI
var data = productions.filter(function(p){return p.panelCodeUI === e});
data.forEach(function(d){
var yval = d.Value;
var xval = d.Date;
var x = [xval, yval];
datamacro.push(x);
});
$(function () {
$(divId).highcharts({
...
})
})
}
That's what you need to parse your data:
charts = [];
$.each(productions.map(function(el) {
return el.PanelCodeUI;
}).filter(function(el, index, arr) {
return arr.indexOf(el) === index;
}), function(index,PanelCodeUI) {
var serie = productions.filter(function(el) {
return el.PanelCodeUI === PanelCodeUI;
});
$.each(serie, function(index, production) {
datamacro.push([production.Value, production.Date]);
});
drawChart('#barchart' + PanelCodeUI, 'LAST FIVE DAYS', datamacro);
});
Also i made this helper function to create the charts:
function drawChart(containerID, chartTitle, data) {
charts.push(new Highchart.Chart({
chart: {
type: 'column',
renderTo: containerID
},
title: {
text: chartTitle
},
subtitle: {
text: ''
},
xAxis: {
type: "datetime",
tickInterval: 24 * 3600 * 1000,
labels: {
rotation: -45,
align: 'right'
},
dateTimeLabelFormats: { // don't display the dummy year
day: '%e. %b',
},
//crosshair: true
},
credits: {
enabled: false
},
yAxis: {
labels: {
enabled: false
},
title: {
text: null
}
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%d/%m/%Y', new Date(this.x)) + '<br/>' + ' in barrels: ' + this.y;
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
},
series: {
pointRange: 24 * 3600 * 1000, // one day
pointInterval: 3600 * 1000
}
},
series: [{
//name: '',
showInLegend: false,
data: data,
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
format: '{point.y:.1f}', // one decimal
y: 10, // 10 pixels down from the top
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
}]
}));
}

Highchart: add href to each segment of stacked bar chart

I want to put specific link on each segment of stacked 100% bar chart..
Demo of stacked bar chart : http://www.highcharts.com/demo/bar-stacked
In details what I am doing and what I am looking for is : Please go to http://barchart.worddss.com/new/ and fill data in left table and submit.
After submit, As you can see each different color segment have a different url but url is like : http://barchart.worddss.com/new/url2&value=2
i.e. I can give fixed url to every fixed color segment and behind value of label..
But I want is, different urls to every segment.. like yellow to google.com , green to fb.com etc..
Code I am using is :
function show () { var m1=document.getElementById('m1').value;
var m2=document.getElementById('m2').value;
var m3=document.getElementById('m3').value;
var m4=document.getElementById('m4').value;
var m5=document.getElementById('m5').value;
var m6=document.getElementById('m6').value;
var m7=document.getElementById('m7').value;
var c1=document.getElementById('c1').value;
var c2=document.getElementById('c2').value;
var c3=document.getElementById('c3').value;
var c4=document.getElementById('c4').value;
var c5=document.getElementById('c5').value;
var c6=document.getElementById('c6').value;
var c7=document.getElementById('c7').value;
var e1=document.getElementById('e1').value;
var e2=document.getElementById('e2').value;
var e3=document.getElementById('e3').value;
var e4=document.getElementById('e4').value;
var e5=document.getElementById('e5').value;
var e6=document.getElementById('e6').value;
var e7=document.getElementById('e7').value;
var seriesData = [];
seriesData.push({
name: "Por cursar",
data: [parseFloat(e7),parseFloat(c7),parseFloat(m7)],
url: ["url1","egg","gfhf"]
});
seriesData.push({
name: "Acreditados",
data: [parseFloat(e6),parseFloat(c6),parseFloat(m6)],
url: "url1"
});
seriesData.push({
name: "Nivel 4",
data: [parseFloat(e5),parseFloat(c5),parseFloat(m5)],
url: "url1"
});
seriesData.push({
name: "Nivel 3",
data: [parseFloat(e4),parseFloat(c4),parseFloat(m4)],
url: "url1"
});
seriesData.push({
name: "Nivel 2",
data: [parseFloat(e3),parseFloat(c3),parseFloat(m3)],
url: "url1"
});
seriesData.push({
name: "Nivel 1",
data: [parseFloat(e2),parseFloat(c2),parseFloat(m2)],
url: "url1"
});
seriesData.push({
name: "Por acreditar",
data: [parseFloat(e1),parseFloat(c1),parseFloat(m1)],
url: "url2"
});
$('#container').highcharts({
chart: {
type: 'bar'
},
credits: {
enabled: false
},
title: {
text: "CURSO ACTUAL"
},
xAxis: {
allowDecimals: false,
categories: ['Español', 'Ciencias', 'Matematicas']
},
yAxis: {
min: 0,
allowDecimals: false,
title: {
text: ""
}
},
legend: {
backgroundColor: '#FFFFFF',
reversed: true
},
plotOptions: {
series: {
cursor: 'pointer',
stacking: 'percent',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textShadow: '0 0 3px black'
}
},
point: {
events: {
click: function () {
window.location =(this.series.options.url + "&value=" + this.y);
// alert(this.series.options.url + "&y=" + this.y);
}
}
}
}
},
series: seriesData
});}
I am not completely sure if you want a url per color (serie) or per true segment (point). Thus I made a hybrid one.
Let's say for some series you need to have link per serie and for another link per point. The former looks more natural if URL is provided together with point value.
seriesData.push({
name: "Por cursar",
data: [{y:1, url:'http://facebook.com'}, {y:2, url:'http://google.com'}, {y:3, url: 'http://amazon.com'}]
});
seriesData.push({
name: "Acreditados",
data: [1, 2, 3],
url: "http://cnn.com"
});
This case you click handler must be
point: {
events: {
click: function () {
var point = this;
if (point.url) { //if url is per point as in Por cursar
window.open(point.url);
} else if (point.series.userOptions.url){ //if url is per serie as in Acreditados
window.open(point.series.userOptions.url);
}
}
}
}
Conplete sample can be found here http://plnkr.co/edit/j3NgoNWa6rwPgBGIJDwm

dynamic highcharts with json data

I m trying to figure it out that is it possible to make the json data fetched dynamically from a database with the help of php and mysql and can be plotted with highcharts that too dynamic auto updating? Any help would be appreciated.
following the code i have tried and is not working properly and want to implement to the the website for 10 lines.
<HTML>
<HEAD>
<TITLE>highchart example</TITLE>
<script type="text/javascript"src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
var chart;
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 2
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData1, 1000);
},
cache: false,
});
}
function requestData1() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series2 = chart.series[1],
shift = series2.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[1].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false,
});
}
$(function () {
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis:
{
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: '',
margin: 80
}
},
series: [
{
name: 'Random data',
data: []
},
{
name: ' hahaha',
data: []
}
],
});
});
});
</script>
</HEAD>
<BODY>
<div id="container"
style="min-width: 728px; height: 400px; margin: 0 auto"></div>
</BODY>
</HTML>
*** the live-server-data.php is as followed:
<?php
// Set the JSON header
header("Content-type: text/json");
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
$y = rand(48,52);
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
You can try with
var options = {
chart: {
renderTo: 'chart',
},
credits: {
enabled: false
},
title: {
text: 'Impression/Click Overview',
x: -20
},
xAxis: {
categories: [{}]
},
tooltip: {
formatter: function() {
var s = '<b>'+ this.x +'</b>';
$.each(this.points, function(i, point) {
s += '<br/>'+point.series.name+': '+point.y;
});
return s;
},
shared: true
},
series: [{},{}]
};
$.ajax({
url: "json.php",
data: 'show=impression',
type:'post',
dataType: "json",
success: function(data){
options.xAxis.categories = data.categories;
options.series[0].name = 'Impression';
options.series[0].data = data.impression;
options.series[1].name = 'Click';
options.series[1].data = data.clicks;
var chart = new Highcharts.Chart(options);
}
});
The highcharts website has some useful articles about working with dynamic data. That is probably the best place to start.
http://www.highcharts.com/docs/working-with-data/preprocessing-live-data
http://www.highcharts.com/docs/working-with-data/preprocessing-data-from-a-database
Try something out, and if you have trouble, come back here with a more specific question showing what you have tried. As it stands, your question is too broad, and will probably get closed.
An ajax request for updating data looks something like:
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is // longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}

Categories