how to create line chart with jqplot using ajax data - javascript

I am trying to create line chart with Jqplot by getting the data from c# controller using ajax.
function getGraph(fcn) {
var turl = '/Rep/ChartBoxPlot/' + fcn;
$.ajax({
type: "POST",
url: turl,
dataType: "json",
success: function (result) {
$('#chart1').empty();
for (var i = 0; i < result.length; i++) {
var temp = result[i]['Date'];
var date = moment(temp).format('MMM DD');
var y = result[i]['Actual'];
var line1 = [date, result[i]['Actual']];
var line2 = [date, result[i]['Forecast']];
// alert(line1);
var plot = $.jqplot('chart1', [line1], {
axes: {
xaxis: {
label: "Forecast",
renderer: $.jqplot.ajaxDataRenderer,
//tickOptions: { formatString: '%I:%M:%S %p' },
//numberTicks: 8,
tickInterval: '15 second'
},
yaxis: {
label: 'Lines'
},
},
});
}
},
error(result) {
alert(result)
}
});
}
html
<div id="chart1" style="height: 400px; width: 900px;
position: relative;" class="jqplot-target">
The data from controller is coming fine but the graph is not plotted. Any suggestions would be appreciated
Thanks

Related

Chart.js - how to have statis lables and populate with dynamic data?

I am working on chart.js and I have data coming from JSON via ajax. See the example below:
[{"timestamp":"06:00:00.000000","true_count":2},{"timestamp":"07:00:00.000000","true_count":5},{"timestamp":"08:00:00.000000","true_count":7},{"timestamp":"09:00:00.000000","true_count":8},{"timestamp":"10:00:00.000000","true_count":12},{"timestamp":"11:00:00.000000","true_count":15},{"timestamp":"12:00:00.000000","true_count":20},{"timestamp":"13:00:00.000000","true_count":17},{"timestamp":"14:00:00.000000","true_count":14},{"timestamp":"16:00:00.000000","true_count":11},{"timestamp":"17:00:00.000000","true_count":19},{"timestamp":"18:00:00.000000","true_count":22},{"timestamp":"19:00:00.000000","true_count":16},{"timestamp":"20:00:00.000000","true_count":14},{"timestamp":"22:00:00.000000","true_count":7}]
The JS code i am using for my chart is below:
// create initial empty chart
var ctx_live = document.getElementById("chLine");
var myChart = new Chart(ctx_live, {
type: 'bar',
data: {
labels: [],
datasets: [{
data: [],
borderWidth: 1,
borderColor:'#00c0ef',
label: 'liveCount',
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Count Per Hour",
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
});
// logic to get new data
var getData = function() {
var _data =[];
var _labels = [];
$.ajax({
url: 'chart_data',
type: "get",
success: function(data) {
full_data = JSON.parse(data);
full_data.forEach(function(key,index) {
_data.push(key.true_count);
_labels.push(key.hour);
});
myChart.data.labels = _labels;
myChart.data.datasets[0].data = _data;
myChart.update();
}
});
};
// get new data every 3 seconds
setInterval(getData, 3000);
Now, this is working fine and shows the true_count over time which is a one-hour basis. Now, the chart is showing only hours with count but what I would like to do is to set the static hours from 12 AM to 11 PM, and for hours for which I don't have data the true_count will be zero, and for those that I have data for, the true count will be assigned to that hour and show on the chart.
Any ideas on how do I do that?
Here is an example:
// create initial empty chart
var ctx_live = document.getElementById("chLine");
var myChart = new Chart(ctx_live, {
type: 'bar',
data: {
labels: [],
datasets: [{
data: [],
borderWidth: 1,
borderColor: '#00c0ef',
label: 'liveCount',
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Count Per Hour",
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
});
// Some constants to be changed later:
const HOUR_TO_START = 0;
const HOUR_TO_END = 23;
// helper:
const intToAmPm = (i) =>
i==0 ? '12 AM' :
i==12 ? '12 PM' :
i < 12 ? i + ' AM' :
(i-12) + ' PM';
// logic to get new data
var getData = function() {
var _data = [];
var _labels = [];
$ajax({
url: 'chart_data',
type: "get",
success: function(data) {
full_data = JSON.parse(data);
let preparedData = {};
full_data.forEach(function(key, index) {
let hour = parseInt(String(key.timestamp).substring(0, 2));
preparedData[hour] = key.true_count;
});
for (let i = HOUR_TO_START; i <= HOUR_TO_END; i++) {
_data.push(preparedData[i] === undefined ? 0 : preparedData[i]);
_labels.push(intToAmPm(i));
}
myChart.data.labels = _labels;
myChart.data.datasets[0].data = _data;
myChart.update();
}
});
};
// get new data every 3 seconds
//setInterval(getData, 3000);
getData();
// THIS IS FOR TESTING. IMITATE BACKEND
function $ajax(param) {
param.success('[{"timestamp":"06:00:00.000000","true_count":2},{"timestamp":"07:00:00.000000","true_count":5},{"timestamp":"08:00:00.000000","true_count":7},{"timestamp":"09:00:00.000000","true_count":8},{"timestamp":"10:00:00.000000","true_count":12},{"timestamp":"11:00:00.000000","true_count":15},{"timestamp":"12:00:00.000000","true_count":20},{"timestamp":"13:00:00.000000","true_count":17},{"timestamp":"14:00:00.000000","true_count":14},{"timestamp":"16:00:00.000000","true_count":11},{"timestamp":"17:00:00.000000","true_count":19},{"timestamp":"18:00:00.000000","true_count":22},{"timestamp":"19:00:00.000000","true_count":16},{"timestamp":"20:00:00.000000","true_count":14},{"timestamp":"22:00:00.000000","true_count":7}]');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chLine"></canvas>

Morris chart with for looped data

I have a morris chart in my code. I get data to the chart as following.
$(document).ready(function(){
$("#month_search").click(function(){
var month_value = $("#month_value").val();
$.ajax({
url: '../../new/seller.php',
type: 'POST',
data: {flag: '4', month_value: month_value},
success: function(data) {
alert(data);
var data_json = JSON.parse(data);
var total_chart = {};
for(i = 0; i < data_json.RESULT.length; i++){
var total_all = parseInt(data_json.RESULT[i].total_cus) + parseInt(data_json.RESULT[i].new_cus);
total_chart=
[{
category: data_json.RESULT[i].cat_name,
value: total_all
}] ;
}
var chart1= Morris.Bar({
element: 'morris-bar-chart',
data:total_chart,
xkey: 'category',
ykeys: ['value'],
labels: ['total customers'],
hideHover: 'auto',
resize: true
});
},
});
});
});
But when showing the chart, only last category is shown. (there are 10 categories in the loop).
How to show all these categories in the chart. Please help.

highchart stockchart facing issue

I have done a line chart and it is working perfectly, except it does not have additional function that a stockchart has.
However I am facing an issue where by,
1) my data does not shows at all but the timing is correct.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
<script>
var numX = [];
var time = [];
var i = 0;
var url = 'ws://127.0.0.1:8080/';
var ws = new WebSocket(url, 'echo-protocol');
ws.onmessage = function(evt)
{
console.log(evt.data);
var data = evt.data;
data = JSON.parse(data);
var x = data.position_x;
numX[i] = x;
time[i] = data.timestamp;
i++;
updateChart();
};
function updateChart()
{
$(function ()
{
Highcharts.setOptions
({
global :
{
useUTC : false
}
});
// Create the chart
$('#container').highcharts('StockChart',
{
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 = 0;//Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);
//}, 1000);
}
}
},
rangeSelector:
{
buttons:
[{
count: 1,
type: 'minute',
text: '1M'
},
{
count: 5,
type: 'minute',
text: '5M'
},
{
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title :
{
text : 'Live Coordinate X data'
},
exporting:
{
enabled: false
},
series :
[{
name : 'Random data',
data :
(function ()
{
// generate an array of random data
var data = [], time = (new Date()).getTime(), i;
for (i = -999; i <= 0; i += 1)
{
data.push
([
time,
Math.round(numX)
]);
}
return data;
}())
}]
});
});
}
</script>

How to show the transition in highchart series graph without refreshing the html webpage?

I am getting JSON data using an api which is being stored in an data.json file.
Later a javascript is using that data.json file and using it to draw highcharts. The JSON File is changing every instant and the data.json file is getting update with the data.I am linking this javascript file to an html file and later running it on chrome browser. As data.json file is changing every instant then the graph corresponding to it is also changing every instant. In order to see the graphs I have to manually refresh to see that graph . How do I show the transitions in the data in the graphs without refreshing the browser.
I DONOT WANT TO REFRESH THE DIV OR EITHER THE ENTIRE HTML PAGE something dynamically.
Reference: https://onedesigncompany.com/
Similar to the transitions in this website.
This is how my graph looks like
This is my html + javascript code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
enter code here<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore.js" type="text/javascript"></script>
<div id="container" style="min-width: 310px; height: 400px; max-width: 800px; margin: 0 auto"></div>
<script type="text/javascript">
$(document).ready(function() {
$("#container").load("index.html");
var options = {
chart: {
renderTo: 'container',
type: 'scatter',
zoomType: 'xy'
},
title: {
text: 'Number of people Versus floor'
},
xAxis: {
title: {
enabled: true,
text: 'Uids'
},
startOnTick: true,
endOnTick: true,
showLastLabel: true
},
yAxis: {
title: {
text: 'Floor'
}
},
legend: {
layout: 'vertical',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF',
borderWidth: 1
},
plotOptions: {
scatter: {
marker: {
radius: 5,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: 'uid: {point.x} , floor: {point.y} '
}
}
},
// series: [{}]
};
$.getJSON('/static/data/data.json', function(data) {
//floor0 data
var floor0=[];
var i,j;
for(i=0;i<data.size;i++)
{
if(data.occupancy_information[i].building=="Academic" && data.occupancy_information[i].floor=="0")
floor0.push(data.occupancy_information[i].uids);
}
var merged0 = [].concat.apply([], floor0);
var result0=[];
result0=merged0.map(Number);
var len0=result0.length;
var iMax0 = len0;
var jMax0 = 2;
var f0 = new Array();
for (i=0;i<iMax0;i++) {
f0[i]=new Array();
for (j=0;j<jMax0;j++) {
f0[i][0]=parseInt(merged0[i]);
f0[i][1]=0;
}
}
//floor1 data
var floor1=[];
for(i=0;i<data.size;i++)
{
if(data.occupancy_information[i].building=="Academic" && data.occupancy_information[i].floor=="1")
floor1.push(data.occupancy_information[i].uids);
}
var merged1 = [].concat.apply([], floor1);
var result1=[];
result1=merged1.map(Number);
var len1=result1.length;
var iMax1 = len1;
var jMax1 = 2;
var f1 = new Array();
for (i=0;i<iMax1;i++) {
f1[i]=new Array();
for (j=0;j<jMax1;j++) {
f1[i][0]=parseInt(merged1[i]);
f1[i][1]=1;
}
}
//floor2 data
var floor2=[];
for(i=0;i<data.size;i++)
{
if(data.occupancy_information[i].building=="Academic" && data.occupancy_information[i].floor=="2")
floor2.push(data.occupancy_information[i].uids);
}
var merged2 = [].concat.apply([], floor2);
var result2=[];
result2=merged2.map(Number);
var len2=result2.length;
var iMax2 = len2;
var jMax2 = 2;
var f2 = new Array();
for (i=0;i<iMax2;i++) {
f2[i]=new Array();
for (j=0;j<jMax2;j++) {
f2[i][0]=parseInt(merged2[i]);
f2[i][1]=2;
}
}
//floor3 data
var floor3=[];
for(i=0;i<data.size;i++)
{
if(data.occupancy_information[i].building=="Academic" && data.occupancy_information[i].floor=="3")
floor3.push(data.occupancy_information[i].uids);
}
var merged3 = [].concat.apply([], floor3);
var result3=[];
result3=merged3.map(Number);
var len3=result3.length;
var iMax3 = len3;
var jMax3 = 2;
var f3 = new Array();
for (i=0;i<iMax3;i++) {
f3[i]=new Array();
for (j=0;j<jMax3;j++) {
f3[i][0]=parseInt(merged3[i]);
f3[i][1]=3;
}
}
//floor4 data
var floor4=[];
for(i=0;i<data.size;i++)
{
if(data.occupancy_information[i].building=="Academic" && data.occupancy_information[i].floor=="4")
floor4.push(data.occupancy_information[i].uids);
}
var merged4 = [].concat.apply([], floor4);
var result4=[];
result4=merged4.map(Number);
var len4=result4.length;
var iMax4 = len4;
var jMax4 = 2;
var f4 = new Array();
for (i=0;i<iMax4;i++) {
f4[i]=new Array();
for (j=0;j<jMax4;j++) {
f4[i][0]=parseInt(merged4[i]);
f4[i][1]=4;
}
}
//floor5 data
var floor5=[];
for(i=0;i<data.size;i++)
{
if(data.occupancy_information[i].building=="Academic" && data.occupancy_information[i].floor=="5")
floor5.push(data.occupancy_information[i].uids);
}
var merged5 = [].concat.apply([], floor5);
var result5=[];
result5=merged5.map(Number);
var len5=result5.length;
var iMax5 = len5;
var jMax5 = 2;
var f5 = new Array();
for (i=0;i<iMax5;i++) {
f5[i]=new Array();
for (j=0;j<jMax5;j++) {
f5[i][0]=parseInt(merged5[i]);
f5[i][1]=5;
}
}
var chart = new Highcharts.Chart(options);
chart.addSeries({
name: 'Ground floor',
data: f0
}, false);
chart.addSeries({
name: 'First Floor',
data: f1
}, false);
chart.addSeries({
name: 'Second Floor',
data: f2
}, false);
chart.addSeries({
name: 'Third Floor',
data: f3
}, false);
chart.addSeries({
name: 'Fourth Floor',
data: f4
}, false);
chart.addSeries({
name: 'Fifth Floor',
data: f5
}, false);
chart.redraw();
});
});
</script>
Keep your ajax /getJson in the set interval and pass the data to your massager function when it returns data every five seconds, this way the page doesn't get refreshed.
Look at this example
var time_interval = 5000;
setInterval(function () {
$.ajax({
url: 'your_path_to_the_api',
data: '',
cache: false,
type: 'POST',
success: function (data) {
$('#container').text(data);
}
});
}, time_interval);
You want to update chart, when your data in the backend is updated. To achieve that you have two ways:
as the other answer states, use AJAX with setInterval, where you will request new data from the backend. The problem is that, your data may be not updated yet, or updated before, so you may miss/late with the graph update.
use websockets (or long polling) with database which will have publish possibility (like Redis). Then create websocket connection between backend and frontend. When connection is set, your database should emit signal that "new data is available" and in the backend gather all new data and send via websocket to the front end, and in front end update data using chart.series[index].setData(new_data).
The second solution of course requires backend: database and server. If this is too much, then you need to use the first one.
You can also consider using some platform which implements natively second solution. For example Meteor.
Why not set a time interval so that it refreshes every 5 seconds?
http://devzone.co.in/automatically-refresh-html-page-div-specific-time-interval/

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