Flot Example: Format data in Flot readable JSON
I recently started learning the flot library. Unfortunately, there aren’t any good examples of how to format the data with JSON in a flot friendly manner. Below is some basic code that should retrieve data from a database, format it and then JSON encode it. I’ve written the example mostly in psuedo-code, most beginners should be able to pick up the key points of the following example.
The script below simply returns JSON, you should create this script in a web accessible directory:
getDataforFlot.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?php $mergedData = array(); //Get the first set of data you want to graph from the database $databaseData1 = someFunctionToGetDataFromDatabase($id); //loop through the first set of data and pull out the values we want, then format foreach($databaseData1 as $r) { $x = $r['x_value']; $y = $r['y_value']; $data1[] = array ($x, $y); } //send our data values to $mergedData, add in your custom label and color $mergedData[] = array('label' => "Data 1" , 'data' => $data1, 'color' => '#6bcadb'); //Get the second set of data you want to graph from the database $databaseData2 = someFunctionToGetDataFromDatabase($id); foreach($databaseData2 as $r) { $x = $r['x_value']; $y = $r['y_value']; $data2[] = array ($x, $y); } //send our data values to $mergedData, add in your custom label and color $mergedData[] = array('label' => "Data 2" , 'data' => $data2, 'color' => '#6db000'); //now we can JSON encode our data echo json_encode($mergedData); ?> |
Next, just put the following JQuery into your page to render the data using AJAX:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | $(document).ready(function(){ $.ajax({ // usually, we'll just call the same URL, a script // connected to a database, but in this case we only // have static example files so we need to modify the // URL url: "/getDataforFlot.php", method: 'GET', dataType: 'json', success: onOutboundReceived }); function onOutboundReceived(series) { var length = series.length; var finalData = series; var options = { lines: { show: true }, points: { show: true, hoverable:true }, grid: { hoverable: true, clickable: true } }; $.plot($("#YOUR-DIV-ID-HERE), finalData, options); } }); |








