I want my flot graph to update it's data on set intervals. I have been unable to find any built in functionality that does this so I intend to do something along the lines of redrawing the graph each time an interval expires. The data parameter being passed to flot is the only value that will change. The data variable is populated using an ajax request to a server method which returns json.
Am I barking up the right tree or is there a better way of doing this?
Also, how do you instantiate a timer (preferably, with a callback that I can pass in to handle the ajax request and flot redraw) in javascript/jquery?
EDIT - Now implemented as below:
$(document).ready(function() {
var options = { xaxis: { mode: 'time' } };
var i = window.setInterval(function() {
$.getJSON('<%= Url.Action("SomeAction", "SomeController") %>', {}, function(jsonData) {
var graphData = new Array();
$.each(jsonData, function(i, series) {
graphData[i] = { label: series.label, data: new Array() };
$.each(series.data, function(j, point) { graphData[i].data[j] = [point.date, point.value]; });
});
var plot = $.plot($('#FlotPlot'), graphData, options);
});
}, 1500);
});
Note that I have an ASP.Net MVC controller that returns json in (almost) the format needed by flot:
public class SomeController : Controller {
public ActionResult SomeAction() {
return Json(new Models.FlotGraph(...).Items);
}
}
public class FlotGraph {
public FlotGraph(...) {
List<FlotSeries> items = new List<FlotSeries>();
...
Items = items.ToArray();
}
public FlotSeries[] Items { get; private set; }
}
public class FlotSeries {
internal FlotSeries(string label, IEnumerable<FlotPoint> data) {
this.label = label;
this.data = data.ToArray();
}
public string label { get; private set; }
public FlotPoint[] data { get; private set; }
}
public class FlotPoint {
internal FlotPoint(DateTime date, float value) {
this.date = (date - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime()).TotalSeconds;
this.value = value;
}
public double date { get; private set; }
public float value { get; private set; }
}