Issues passing json data to build morris.js plot dynamically - ajax

I want to build a morris.js plot dynamically by using ajax, php, and mysql.
i have been searching with no success how to achieve this.
I get the array data successfully with ajax but now i can't pass these data to build the plot.
From the PHP script i get the following json array:
[{"concurso":"2736","R1":"7","R2":"24","R3":"27","R4":"39","R5":"45","R6":"52","R7":"12"},{"concurso":"2737","R1":"16","R2":"19","R3":"23","R4":"29","R5":"33","R6":"49","R7":"36"},{"concurso":"2738","R1":"4","R2":"6","R3":"20","R4":"21","R5":"45","R6":"55","R7":"38"},{"concurso":"2739","R1":"5","R2":"16","R3":"17","R4":"24","R5":"41","R6":"47","R7":"36"},{"concurso":"2745","R1":"1","R2":"13","R3":"19","R4":"29","R5":"41","R6":"46","R7":"50"}]
Where morris.js y is the value after 'concurso', and ykeys are the values after R1, R2, R3, ... R7.
My jQuery looks like this so far:
$.ajax({
url: "ajax/default_chart_numbers.php",
cache: false,
dataType: "json",
timeout:3000,
success : function (data) {
new Morris.Line({
// ID of the element in which to draw the chart.
element: 'revancha',
data: $.parseJSON(data),
xkey: 'concurso',
ykeys: ['R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7'],
labels: ['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7'],
hideHover: 'auto',
resize: true
});
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
}
});
I can't see the plot. There's nothing. What am i missing?
Well, fortunately i could fix it myself. Here is my working jQuery ☺:
$.ajax({
url: "ajax/some_handler.php",
cache: false,
type: "POST",
data: {anyVar: 'specialValue4PHPScriptAndDataBaseFilter'},
dataType: "json",
timeout:3000,
success : function (data) {
//console.log(data); alert(JSON.stringify(data));
Morris.Line({
element: 'TheElementName',
data: data,
xkey: 'someID',
ykeys: ['R1', 'R2', 'R3', 'R4', 'R5', 'R6'],
labels: ['n1', 'n2', 'n3', 'n4', 'n5', 'n6'],
hideHover: 'auto',
resize: true
});
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
} /*References: http://stackoverflow.com/questions/22746646/ajax-i-cant-get-data-from-php-by-using-json-encode*/
});

You can use the setData() function on the Morris.Line returned object to update data. Here is a snippet from the morris examples which I've commented. (https://github.com/morrisjs/morris.js/blob/master/examples/updating.html)
// build array filled with placeholder data
var nReloads = 0;
function data(offset) {
var ret = [];
for (var x = 0; x <= 360; x += 10) {
var v = (offset + x) % 360;
ret.push({
x: x,
y: Math.sin(Math.PI * v / 180).toFixed(4),
z: Math.cos(Math.PI * v / 180).toFixed(4)
});
}
return ret;
}
// create the morris chart.
var graph = Morris.Line({
element: 'graph',
data: data(0),
xkey: 'x',
ykeys: ['y', 'z'],
labels: ['sin()', 'cos()'],
parseTime: false,
ymin: -1.0,
ymax: 1.0,
hideHover: true
});
// update the chart with the new data.
function update() {
nReloads++;
// called on the returned Morris.Line object.
graph.setData(data(5 * nReloads));
$('#reloadStatus').text(nReloads + ' reloads');
}
setInterval(update, 100);

Related

Updating Dygraph with ajax

I have below code which pull data from mysql using ajax json and draw Dygraph chart which it works fine but when my problem is updating the chart.
When I try to update the graph I am getting this error:
Uncaught ReferenceError: g is not defined
which is already defined
all these code are in document ready fucntion
// get data from server
$.ajax({
type: 'POST',
url: 'php/proccess.php',
data: {
type: "jobgraph",
job: job
},
dataType: "json",
success: function(response) {
//console.log(response);
var i = 0;
$.each(response, function(key, value) {
test[i] = [new Date(value[0]), value[1] / 1000, value[2]];
i++;
});
if (test) {
document.addEventListener("mousewheel", function() {
lastClickedGraph = null;
}, false);
document.addEventListener("click", function() {
lastClickedGraph = null;
}, false);
if (response) {
var g = new Dygraph(document.getElementById("noroll"),
test, {
labels: ["Date", "Voltage", "Temp"],
digitsAfterDecimal: 3,
interactionModel: {
'mousedown': downV3,
'mousemove': moveV3,
'mouseup': upV3,
'click': clickV3,
'dblclick': referesh,
'mousewheel': scrollV3
}
}
);
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
alert('Internal error: ' + jqXHR.responseText);
} else {
console.log(errorThrown);
}
},
});
// update Data every 2 second by pulling new data from mysql server
window.intervalId = setInterval(function() {
$.ajax({
type: 'POST',
url: 'php/proccess.php',
data: {
type: "jobgraph",
job: job
},
dataType: "json",
success: function(response) {
//console.log(response);
var i = 0;
$.each(response, function(key, value) {
test[i] = [new Date(value[0]), value[1] / 1000, value[2]];
i++;
});
//console.log(test);
g.updateOptions({
'file': test
});
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
alert('Internal error: ' + jqXHR.responseText);
} else {
console.log(errorThrown);
}
},
});
}, 2000); </pre>
//end update
In your setup, you define the graph with:
var g = new Dygraph(...
var limits the scope of g, so it's not accessible in your later call. Make the g variable available globally, or in a variable that you pass between functions.

fullcalendar pass in array to set events

I would like to pass in an array of IDs that will be used to select the events I want to display. The fullcalendar displays all of the events if I do not use the 'data' attribute with the ID array. When the data attribute is added I get the error message 'There was an error fetching events!'
This is the document ready function:
var groupSelectedArray = [];
groupSelectedArray[0] = '1';
groupSelectedArray[1] = '2';
$('#calendar').fullCalendar({
header:
{
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
titleFormat: {month: 'MMMM'},
defaultView: 'month',
editable: false,
events: function (start, end, groupSelectedArray, callback) {
$.ajax({
type: "POST",
url: '#Url.Action("GetAllEvents", "Home")',
data: { selectedGroups: groupSelectedArray },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
var events = [];
$(doc).each(function () {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start'),
end: $(this).attr('end'),
id: $(this).attr('id'),
description: $(this).attr('description'),
color: $(this).attr('color'),
textColor: 'black'
});
});
callback(events);
} ,
error: function () {
alert("There was an error fetching events!")
}
});
}
This is the C# method:
public JsonResult GetAllEvents(string[] selectedGroups)
{
var eventList = GetEventsFromDatabase(selectedGroups);
var rows = eventList.ToArray();
return Json(rows, JsonRequestBehavior.AllowGet);
}
Can anyone see where I am going wrong?
Thanks.
What I did to get this to work was change the 'data' part of the ajax call:
Replace this:
{ selectedGroups: groupSelectedArray },
to this:
data: JSON.stringify(groupData),

How can I generate a real-time highchart from my database data?

I have looked at the following links Binding json result in highcharts for asp.net mvc 4 , highcharts with mvc C# and sql, HighChart Demo and many others. However, I couldn't find a working demo showing how to implement a highchart using data from a database.
Objective:
I want to generate a real time highchart line graph getting data from my database. What I want is very similar to the third link which provides a real-time highchart with randomly generated values. It is also similar by X-axis and Y-axis, for I want my x-axis to be "Time" (I have a DateTime column in my database) and y-axis to be an integer (I have a variable for that as well in my database).
Please I need help in sending the model data to my razor view.
Note that I am already using SignalR to display a realtime table. I also want to know if it can be used to automatically update the highchart as well.
Below is the code snippet of my script in the view. I have used the code provided in link 3 for generating the highchart. Please tell me where should I apply the changes on my code.
#section Scripts{
<script src="~/Scripts/jquery.signalR-2.2.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/SignalR/Hubs"></script>
<script type="text/javascript">
$(document).ready(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.dataHub;
//debugger;
// Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function () {
getAllMessages()
};
// Start the connection.
$.connection.hub.start().done(function () {
alert("connection started")
getAllMessages();
}).fail(function (e) {
alert(e);
});
//Highchart
Highcharts.setOptions({
global: {
useUTC: false
}
});
//Fill chart
$('#container').highcharts({
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 = Math.random();
series.addPoint([x, y], true, true);
}, 1000);//300000
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
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: Math.random()
});
}
return data;
}())
}]
});
});
function getAllMessages() {
var tbl = $('#messagesTable');
var data = #Html.Raw(JsonConvert.SerializeObject(this.Model))
$.ajax({
url: '/home/GetMessages',
data: {
id: data.id,
},
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
tbl.empty().append(result);
$("#g_table").dataTable();
}).error(function (e) {
alert(e);
});
}
</script>
}
UPDATED CODE
//Highchart
Highcharts.setOptions({
global: {
useUTC: false }
});
//Fill chart
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: $.connection.hub.start().done(function () {
alert("Chart connection started")
var point = getAllMessagesforChart();
var series = this.series[0];
setInterval(function (point) {
// add the point
series.addPoint([point.date_time, point.my_value], true, true)
}, 1000);
}).fail(function (e) {
alert(e);
})
}
}
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: []
}]
});
function getAllMessagesforChart() {
var data = #Html.Raw(JsonConvert.SerializeObject(this.Model))
$.ajax({
url: '/home/GetMessagesforChat',
data: {
id: data.id,
},
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (data) {
data = JSON.parse(data);
//data_graph = [].concat(data);
//$("#debug").html(data_graph);
}).error(function (e) {
alert(e);
});
return data;
//return data_graph;
}
There is an example that might help you:
http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-ajax/
it uses an ajax callback function.
Well, you can also have a look at my sample where I add dynamically series by clicking add button.
http://plnkr.co/edit/Sh71yN?p=preview
You only need to add data in the right structure.
Have a look at the function
$("#btnAdd").click(function()
of my code script.js
I hope it helps.
regards,
Luis

Dynamic Flot chart using Ajax

I'm new to javascript and flot and hope someone can help me with this problem I'm having.
What I'm trying to achieve it have a dynamic flot graph on a page.
The data for the series that is to be plotted is in a file that will get updated every few seconds. I want the flot graph to read the data file every few seconds and be updated with the new data.
Here's the code I've got which isn't working. The graph displays ok on page load, but just doesn't get updated every 5 seconds.
Any help is much appreciated.
$(function () {
var dataFolder = "http://localhost/graphdata/";
/***********************************************************************
* Function to get series data from a file
***********************************************************************/
function getSeriesData(file) {
var url= dataFolder + file;
var data = null;
$.ajax({
async: false,
url: url,
method: 'GET',
dataType: 'json',
success: function(datasets){
data = datasets;
},
error: function(error,text,http){
alert(error + " " + text + " " + http);
}
});
return data;
}
var plot = $.plot($("#placeholder"),
[
{label: "A", data: getSeriesData("dataA.txt")},
{label: "B", data: getSeriesData("dataB.txt")},
{label: "C", data: getSeriesData("dataC.txt")}
],
{
series: {
lines: {
color: "red",
show: true
},
points: {
show: true
},
shadowSize: 0,
hoverable: true
},
colors: ["red", "blue", "green"],
yaxis: {
min: 0, ticks:5
},
xaxis: {
mode: 'time',
timeformat: '%H:%m',
show: false
},
legend:{
show: true
},
grid:{
color: "green",
show: true,
backgroundColor: "white",
hoverable: true
}
}
);
var updateInterval = 1000 * 5;
function update() {
plot.setData([
{label: "A", data: getSeriesData("dataA.txt")},
{label: "B", data: getSeriesData("dataB.txt")},
{label: "C", data: getSeriesData("dataC.txt")}
]);
plot.setupGrid();
plot.draw();
setTimeout(update, updateInterval);
}
update();});
I figured it out. The ajax call for the file was being cached in the browser so any further calls for the same file would have been returned from cache, making it look like no updates to the graph were happening. Switch caching of in the function and it works fine now.
function getSeriesData(file) {
var url= dataFolder + file;
var data = null;
$.ajax({
async: false,
cache: false,
url: url,
method: 'GET',
dataType: 'json',
success: function(datasets){
data = datasets;
},
error: function(error,text,http){
alert(error + " " + text + " " + http);
}
});
return data;
}
It seems to update correctly for me using numbers. Can you provide a few data examples?
I changed the x axis and data pull but the updating worked fine.
function getSeriesData() {
var randomnumber=Math.floor(Math.random()*11)
var randomnumber2=Math.floor(Math.random()*11)
var data = [
[randomnumber, randomnumber2],
[randomnumber +1, randomnumber2 +2],
[randomnumber +3, randomnumber2 +4],
[randomnumber +5, randomnumber2 +6],
[randomnumber +7, randomnumber2 +8],
];
return data;
}
fiddle - http://jsfiddle.net/EX6dv/1/
It seems you need to put following out side the update function too.
setTimeout(update, updateInterval);

How to refresh jqplot bar chart without redrawing the chart

I have a jqplot bar chart and I want the chart data to be changed when the user changes the value on a drop-down list. That works, but the problem is the bar chart redraws, one over another, each time the user changes the values.
How can I update or reload the bars without drawing the whole thing again? Is there any property value to be set?
Chart data changes according to an ajax call:
$.ajax({
url: '/Home/ChartData',
type: 'GET',
data: { Id: Id },
dataType: 'json',
success: function (data) {
$.jqplot('chartDiv', [a, b], CreateBarChartOptions(xAxis));
}});
function CreateBarChartOptions(xAxis) {
var optionsObj = {
title: 'Stat',
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: xAxis
},
yaxis: { min: 0 }
},
series: [{ label: 'A' }, { label: 'B'}],
seriesDefaults: {
shadow: true,
renderer: $.jqplot.BarRenderer,
rendererOptions: {
barPadding: 8,
barMargin: 10
}
},
};
return optionsObj;
}
A reply would be highly appreciated. Thanks.
What you want to do is call jqPlot's .replot() method when you draw the new chart. Change your ajax call to look like this:
$.ajax({
url: '/Home/ChartData',
type: 'GET',
data: { Id: Id },
dataType: 'json',
success: function (data) {
$.jqplot('chartDiv', [a, b], CreateBarChartOptions(xAxis)).replot();
}});
Try having your chart object as a global variable in your script as:
var plot1 = $.jqplot('chartDiv', [a, b], CreateBarChartOptions(xAxis));
Then on success reset the data, axesScale and replot as:
var newData = [['a',1],['b',2],['c',3]];
plot1.series[0].data = newData;
plot1.resetAxesScale();
plot1.replot();
Ref: https://groups.google.com/group/jqplot-users/browse_thread/thread/59df82899617242b?pli=1
Each time before redrawing the graph, just destroy the existing1.
$.ajax({
url: '/Home/ChartData',
type: 'GET',
data: { Id: Id },
dataType: 'json',
success: function (data) {
if(plot)
{
plot.destroy();
}
var plot=$.jqplot('chartDiv', [a, b], CreateBarChartOptions(xAxis));
}});
Took me a while to find an answer for the script generated data, so I'm going to post this right here. I used a combination of the above code.
I created a global var, named plot3 within my script file. Then created the below function. When this is called with a redraw boolean, it determines if I need to destroy and redraw or draw for the first time.
What first bit of code does is gets data from my jqgrid, (which is being updated in a different function), and updates the arrays. The second bit, determines my interval ticks, on the x-axis dependent upon my length of data.
function DrawGraph(bRedraw){
var testTimes = [];
testTimes = $('#polarizationTable').jqGrid('getCol', 'TestTime', testTimes, false);
var RdgA = $('#polarizationTable').jqGrid('getCol', 'RdgA', RdgA, false);
var RdgB = $('#polarizationTable').jqGrid('getCol', 'RdgB', RdgB, false);
var readingLineA = [];
for (var i=0; i<testTimes.length; i++){
readingLineA.push([testTimes[i], RdgA[i]]);
}
var readingLineB = [];
for (var i=0; i<testTimes.length; i++){
readingLineB.push([testTimes[i], RdgB[i]]);
}
var maxX = $("#testLength").val();
var lengthX = testTimes.length;
var tickIntervalX = Math.round(maxX/10);
if(bRedraw == true)
{
plot3.destroy();
bRedraw = false;
}
if(bRedraw == false)
{
plot3 = $.jqplot('chart3', [readingLineA, readingLineB],
{
title:'Graph',
series:[{label:'Reading - A'}, {label:'Reading - B'} ],
legend:{show:true, location:'se'},
// You can specify options for all axes on the plot at once with
// the axesDefaults object. Here, we're using a canvas renderer
// to draw the axis label which allows rotated text.
axes:{
xaxis:{
label:'Minutes',
syncTicks: true,
min: 0,
numberTicks: 10,
tickInterval: tickIntervalX,
max: maxX*1.1,
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
labelOptions: {
fontSize: '12pt'
},
},
yaxis:{
label:'Data',
min: 0,
numberTicks: 10,
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
labelOptions: {
fontSize: '12pt'
}
},
}
});
}
}
Here is a full example of how to dynamically update the plot with new data without reloading the page:
<div id="chart1" style="height: 300px; width: 500px; position: relative;"></div>
<button>New data point</button>
<script type="text/javascript">
var storedData = [3, 7];
var plot1;
renderGraph();
$('button').click( function() {
doUpdate();
});
function renderGraph() {
if (plot1) {
plot1.destroy();
}
plot1 = $.jqplot('chart1', [storedData]);
}
function doUpdate() {
var newVal = Math.random();
storedData.push(newVal);
renderGraph();
}
</script>
It's a simplified version of this guy's post: JQPlot auto refresh chart with dynamic ajax data
$('#chart).html('');
chart is the DIV where chart is created.
this does the trick, nothing fancy by effective.
Maybe this will help. I on the other hand is having problem with getting replot to work at all, but i'am using a dataRenderer.
$.ajax({
url: '/Home/ChartData',
type: 'GET',
data: { Id: Id },
dataType: 'json',
success: function (data) {
$('chartDiv').empty();
$.jqplot('chartDiv', [a, b], CreateBarChartOptions(xAxis));
}});
hope this helps
jQuery(document).ready(function(){
jQuery.ajax({
url: '/review_graphs/show',
type: 'GET',
success: function (data) {
var plot1 = jQuery.jqplot('chartDiv', [data,data],
{
title: 'Bianual Reviews percentage',
series:[
{
renderer:jQuery.jqplot.BarRenderer,
label:'Average',
stackSeries: true,
dragable: {color: '#ff3366',constrainTo: 'x'},
trendline:{show: false}
},
{
label:'Trend Line',trendline:{show: false}}
],
legend: {
show: true,
placement: 'outsideGrid'
},
axesDefaults: {
tickRenderer: jQuery.jqplot.CanvasAxisTickRenderer ,
tickOptions: {
angle: -30,
fontSize: '10pt'
}
},
axes: {
xaxis: {
renderer: jQuery.jqplot.CategoryAxisRenderer
}
}
});
}});
});
The best method I got is, the div in which you're drawing, clear that before you draw your new graph.
$('#graph_area).children().remove();

Resources