Very new to both JSON and jQuery, but here is what I am trying to do - I am returning a JSON string to my webpage as part of a bigger report model in order to create a number of graphs (using jqPlot) at the same time the report is generated.
To practice with these charts, I was using the following tutorial - Tutorial
Here is the jQuery from this tutorial -
jQuery(document).ready(function() {
urlDataJSON = '/Graph/HearthRateDataJSON';
$.getJSON(urlDataJSON, "", function(data) {
var dataLines = [];
var dataLabels = "";
$.each(data, function(entryindex, entry) {
dataLines.push(entry['Serie']);
dataLabels = dataLabels + entry['Name'];
});
Plot(dataLines, dataLabels);
});
});
function Plot(dataLines, dataLabels) {
var line1 = "{ label: 'line1.0' }";
options = {
legend: { show: true },
title: 'Heart rate overview',
axesDefaults: { pad: 1 },
seriesDefaults: { showMarker: false, trendline: { show: false }, lineWidth: 3 },
axes: {
yaxis: { min: 0, autoscale: true, label: 'HR[bpm]', labelRenderer: $.jqplot.CanvasAxisLabelRenderer },
xaxis: { autoscale: true, label: 'Time', labelRenderer: $.jqplot.CanvasAxisLabelRenderer }
}
};
//Data from database is already an array!
plot = $.jqplot('chartdiv', dataLines, options);
plot.redraw(); // gets rid of previous axis tick markers
}
To retrieve the JSON data, this tutorial uses the getJson() method to point to a link. I have the JSON string ready to pass through to the jQuery however, e.g.
[
{"Name":"Patient","Serie":[[1,4],[2,25],[3,7],[4,14],[5,13]]},
{"Name":"Test","Serie":[[1,13],[2,5],[3,7],[4,20],[5,17]]}
]
In the jqPlot examples, they pass hardcoded data through as follows:
$(document).ready(function(){
var plot1 = $.jqplot ('chart1', [[3,7,9,1,4,6,8,2,5]]);
});
However, my automatically generated JSON string has the curly braces, etc. Is there a way to pass this through to jQuery without using the getJson method?
EDIT-Pie Chart Jquery Code
$(document).ready(function () {
var data4 = '[{ "Label": "Car", "Value": 9 },{ "Label": "Bus", "Value": 2 },{ "Label": "Train", "Value": 7 },{ "Label": "Plane", "Value": 8 },{ "Label": "Boat", "Value": 4 }]';
var data = $.parseJSON(data4);
var plot1 = jQuery.jqplot('pieChart', [data],
{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
legend: { show: true, location: 'e' }
}
);
});