I've created a chart and I want to update in real time, that's why I use ajax. My question is, how to display the ajax response? Below is my sample script of my chart. Please help me. Thank you very well.
Chart.php -
$(document).ready(function () {
Highcharts.chart('container', {
chart: {
type: 'bar'
},
title: {
text: "TITLE"
},
series: [{
name: 'Present',
data: [*//must display the ajax response here//*]
}]
});
});
ajax.php
<script>
function fanc_no(){
$.ajax({
url: "test.php",
success: function(result){
$("#container").html(result);
}
});
}
window.setInterval(function(){
func_no();
}, 1000);
</script>
Take a look at the load function:
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.round(Math.random() * 100);
series.addPoint([x, y], true, true);
}, 1000);
}
}
}
Now, inside the setInterval function, you have to call your ajax and pass the result as shown.
Take a look at the official docs for it.
I have a problem on my HighCharts graph with JSON data. To explain a litle bit : I have a form, when I submit this form I send my data to my controller with Ajax, I treat them and I return the new array of data for my highcharts graph, but when I use setData function with my new array the graph disappear and the new data aren't displayed.
Here is my ajax function and my test to set the new data into my graph :
$('#gestion .l-gestion-content-form #form-add-informations .btn-validation').click(function(e) {
e.preventDefault();
var chart = $('#hightchart-graf').highcharts();
var dataActionForm = $('#form-add-informations').attr('action').split("/");
var url_ajax = Routing.generate('gestion_view', { dossier: dataActionForm[4], fille: dataActionForm[5] });
var formData = $('#form-add-informations').serializeArray();
$.ajax({
type: "POST",
dataType: 'json',
url: url_ajax,
data: formData,
success: function(msg)
{
console.log(msg['infosArray']);
var test = [ msg['infosArray'].join(',') ];
console.log(test);
console.log('---------------------------------------------');
console.log(msg.infosArray);
var test2 = msg.infosArray.join(',');
var test3 = test2.replace('"', '');
console.log(test2);
chart.series[0].setData( [ msg.infosArray.join(',') ] );
//[ {{ msg.infosArray | join(',') }} ]
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('ERROR');
}
});
});
All my data are stored in the array named msg.infosArray or msg['infosArray'] and the first console.log return an array like this :
["[Date.UTC(2015,11,23),80.00]", "[Date.UTC(2015,11,23),89.00]", "[Date.UTC(2015,11,25),150.00]", "[Date.UTC(2015,11,28),45.00]", "[Date.UTC(2015,11,29),169.00]", "[Date.UTC(2015,11,29),189.00]", "[Date.UTC(2015,11,29),196.00]", "[Date.UTC(2015,11,29),200.00]", "[Date.UTC(2015,11,29),205.00]", "[Date.UTC(2015,11,30),210.00]", "[Date.UTC(2015,11,31),225.00]", "[Date.UTC(2016,0,1),250.00]", "[Date.UTC(2016,0,2),25.00]", "[Date.UTC(2016,0,3),259.00]", "[Date.UTC(2016,0,5),25.00]", "[Date.UTC(2016,0,6),250.00]", "[Date.UTC(2016,0,7),25.00]", "[Date.UTC(2016,0,8),250.00]", "[Date.UTC(2016,0,9),25.00]", "[Date.UTC(2016,0,10),250.00]", "[Date.UTC(2016,0,11),25.00]", "[Date.UTC(2016,0,12),250.00]", "[Date.UTC(2016,0,25),25.00]", "[Date.UTC(2016,0,26),250.00]"]
So I tried to escape " and ' or to join the array but nothing work. Somebody know how can I set the new data, or where I commited a fault ?
Maybe i got a bad response from my Controller ?
Thanks
You need to convert string of javascript code to array of javascript.
I wrote a demo version which converts string to javascript code. and draws chart as expected. Do not focus on the labels it's a dummy data.
JSFiddle Demo
$(function () {
var data = ["[Date.UTC(2015,11,23),80.00]", "[Date.UTC(2015,11,23),89.00]", "[Date.UTC(2015,11,25),150.00]", "[Date.UTC(2015,11,28),45.00]", "[Date.UTC(2015,11,29),169.00]", "[Date.UTC(2015,11,29),189.00]", "[Date.UTC(2015,11,29),196.00]", "[Date.UTC(2015,11,29),200.00]", "[Date.UTC(2015,11,29),205.00]", "[Date.UTC(2015,11,30),210.00]", "[Date.UTC(2015,11,31),225.00]", "[Date.UTC(2016,0,1),250.00]", "[Date.UTC(2016,0,2),25.00]", "[Date.UTC(2016,0,3),259.00]", "[Date.UTC(2016,0,5),25.00]", "[Date.UTC(2016,0,6),250.00]", "[Date.UTC(2016,0,7),25.00]", "[Date.UTC(2016,0,8),250.00]", "[Date.UTC(2016,0,9),25.00]", "[Date.UTC(2016,0,10),250.00]", "[Date.UTC(2016,0,11),25.00]", "[Date.UTC(2016,0,12),250.00]", "[Date.UTC(2016,0,25),25.00]", "[Date.UTC(2016,0,26),250.00]"];
//t = t.map(function(element){return eval(element);});
data = data.map(function (e) {
return eval(e);
});
data = data.map(function (e) {
return [(new Date(e[0])).toLocaleString(), e[1]]
});
var categories = data.map(function (e) {
return (new Date(e[0])).toLocaleString()
});
// t[0] = [date = new Date(t[0])];
$('#container').highcharts({
title: {
text: 'Monthly Average Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: WorldClimate.com',
x: -20
},
xAxis: {
categories: categories
},
yAxis: {
title: {
text: 'Temperature (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'Tokyo',
data: data
}]
});
});
My target: I want to draw HighStock-chart with multiple series. Data is loaded by AJAX from data.php. The output of data.php is an JSON-Array
My problem: I don't know hot to grab the data from JSON Array
The output is e.g
[[timestamp,value1,value2],[timestamp,value1,value2]]
Series 1 should be -> timestamp and value1
Series 2 should be -> timestamp and value2
This is my code
// Draw the chart
$(function(){
/* The chart is drawn by getting the specific data from "data.php".
* The configuration settings are transmitted by GET-Method. The output is an JSON-Array. */
$.getJSON('data.php',
function(data) {
chart = new Highcharts.StockChart
({
chart: { renderTo: 'chartcontainer', type: 'line' },
title: { text: 'You see the data of the last hour!' },
xAxis: { type: 'datetime', title: { text: 'time' } },
yAxis: { title: { text: 'unit' } },
series: [{ name: 'series1', data: data },{ name: 'series2', data: data }],
});
});
});
I think i have to change
series: [{ name: 'series1', data: data },{ name: 'series2', data: data }],
But I dont know in to what
Iterate through all items of the data array, and populate two separate arrays:
var series1 = [];
var series2 = [];
for (var i = 0; i < data.length; i++) {
series1.push([data[0], data[1]);
series1.push([data[0], data[2]);
}
You then have the timestamp-value pairs in each of the series arrays.
Doing this in php might be more efficient, especially if you can replace the current json creation.
I'd like to know the proper way to make a dashboard with multiple highcharts in a single page, I'm loading data to the charts with AJAX from a PHP method.
With 1 chart I'm doing it like this:
Controller
public function random_values(){
//CakePHP code
$this->autoRender = FALSE;
header("Content-type: text/json");
$x = time() * 1000;
$y = rand(1,100);
$ret = array($x, $y);
echo json_encode($ret);
}
View
<script type="text/javascript">
var chart; //global
function requestData() {
$.ajax({
url: 'singlecharts/random_values',
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(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(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: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
</script>
But how do I do to make many charts, everyone with its own ajax request.
Any help will be appreciated it, thank you.
EDIT
This is what I've tried so far and isn't working.
Controller:
public function random_one(){
$this->autoRender = FALSE;
//Set the JSON header
header("Content-type: text/json");
//The x value is the current JavaScript time, ...
$x = time() * 1000;
//The y value is a random number
$y = rand(1,100);
//Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
}
public function random_two(){
$this->autoRender = FALSE;
//Set the JSON header
header("Content-type: text/json");
//The x value is the current JavaScript time, ...
$x = time() * 1000;
//The y value is a random number
$y = rand(1,100);
//Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
}
View
<script type="text/javascript">
var chart; //global
function requestData() {
$.ajax({
url: 'charts/random_one',
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(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data one'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data #1',
data: []
}]
});
});
var chart2; //global
function requestDataTwo() {
$.ajax({
url: 'charts/random_two',
success: function(point) {
var series = chart2.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
// add the point
chart2.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart2 = new Highcharts.Chart({
chart: {
renderTo: 'container-two',
defaultSeriesType: 'spline',
events: {
load: requestDataTwo
}
},
title: {
text: 'Live random data two'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data #2',
data: []
}]
});
});
</script>
The problem was that Highcharts demo tells you to render the chart in "container" div and CakePHP default layout also uses a "container" div. There was a conflict between those two.
Thank you guys.
Your setTimeout(requestData, 1000); is the same in both requestData and requestDataTwo. You need them both to be independent of each other, otherwise, the one will always return with not 1, but twice the number of requests...
function requestDataTwo() {
$.ajax({
url: 'test.php?random_two',
success: function(point) {
var series = chart2.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
// add the point
chart2.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1000); **<-- Change this here to requestDataTwo**
},
cache: false
});
}
Just as well... You need to add this to your php "controller"
<?php
switch (key($_GET)) {
case 'random_two':
random_two();
die();
break;
case 'random_one':
random_one();
die();
break;
}
?>
Have you checked similar posts here on stack overflow?
Cannot display multiple Highcharts on a single page
Manage multiple highchart charts in a single webpage
Using multiple Highcharts in a single page
Create six chart with the same rendering,different data (highchart )
It could also help to view the source of the Highcharts demo page that has many charts on one page, and see how they are called.
Highcharts demo
Sorry I can´t help more. Might have more time later this evening :)
If you want to use multiple charts on a single page first of create different variables for all the charts like var chart1, chart2;
Now on $(document).ready define all the chart variables for different charts and give appropriate properties especially renderTo property. You can define different ajax calls for different charts by using separate load events for charts.
I'm trying to create some Highstock charts (Highcharts) using sampled data but all I get when I run it its a blank page.
This is my php code:
<?php
header("Content-type: text/json");
$horas_muertas = array(array(1296518400000,4),array(1296604800000,2),array(1296691200000,3),array(1296777600000,3));
$horas_trabajadas = array(array(1296518400000,2),array(1296604800000,3),array(1296691200000,4),array(1296777600000,5));
$datos = array(json_encode($horas_muertas),json_encode($horas_trabajadas));
$datosj = json_encode($datos);
echo $datosj[0];
?>
As you can see I tried accesing the first location of the JSON, which returned this so I'm sure something's wrong there:
[
But when I use this code for the chart(I removed non-relevant code):
function requestData() {
$.ajax({
url: 'data.php',
datatype: 'json',
success: function(data) {
//alert(data);
chart.series[0].setData(data[0]);
chart.series[1].setData(data[1]);
},
cache: false
});
}
$(function() {
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'container',
type: 'column',
events: {
load: requestData
}
},
series: [{
name: 'Horas Prendidas',
data: []},
{
name: 'Horas Trabajadas',
data: []}]
});
});
All I get is a blank page,when I at least should get a chart without any data on it, any ideas on how to solve this? Help is much appreciated
Use chart.series[0].addPoint(data[0]); instead of chart.series[0].setData(data[0]);