Follow me

Sunday, January 12, 2014

Charts And Graphs Using ChartJS, Ajax, Spring 3, Json

Web applications now these days are in demanding state, they have a huge data with them and user want to make this data more effective, interesting easy to understand , easy to analyse and compare.

Graphs and charts are the best way to present data in logical manner.

In this article I am going to explain you very easy and efficient way to draw the different graphs using chartjs 

see the link for more detail http://www.chartjs.org/

This chartJs provide javascript Chart.js which is easy and object oriented client side java script.
These graphs require the data in the form of Json object.

Here we are going to make an ajax request to spring action  for data and display the PIE chart for that data.

Below are the steps you need to follow.

1.  First we need to include the Chart.js library in the JSP page. The library occupies a global variable of Chart.
<script src="resources/scripts/jquery-1.9.1.js"></script>
<script src="resources/scripts/jquery-ui.js"></script>
<script src="resources/scripts/Chart.js"></script>
<script src="resources/scripts/legend.js"></script>
 JQuery I used for making AJAX call and to use its other utility method like parseJSON().

       Here you can see the legend.js , legend is table explaining symbol used on chart like which color indicate what. Chart.js do not provide this facility so legends. js is an extension to Chart.js to add graph legends

You can download this javascript extension form here
https://github.com/bebraw/Chart.js.legend/tree/master/src


2. To create a chart, Chart.js need html 5 canvas tag as place holder 

    
<td >
                <canvas id="canvas" height="250" width="300"></canvas>
                <div id="canvasLegend"></div>
</td>

Legend is table explaining symbol used on chart also this <div> canvasLegend is place holder for displaying legends


3. Ajax call to get the Json data as response. Here we are using JQuery Ajax to call the spring action         getReportData which will return the Json object.   
    
   We are parsing the string in the form of Json object using jQuery.parseJSON(response)

<script type="text/javascript">

function showPieChart() {
      
       $.ajax({
              type: "GET",
              url: "/appname/getReportData",
              cache: false,                    
              contentType: "application/json; charset=utf-8",
              success: function(response){
                    
var responsePIE = jQuery.parseJSON(response);
var myPieChart = new Chart(document.getElementById("canvas").getContext("2d")).Pie(responsePIE);
legend(document.getElementById("canvasLegend"), responsePIE);
              },
              error: function(response){              
                     alert('Error while request..');
                    
              }
       });
      
}            

</script>

           To create a chart, we need to instantiate the Chart class.

            To do this, we need to pass in the 2d context of where we want to draw the chart.

var myPieChart = new Chart(document.getElementById("canvas").getContext("2d")).Pie(responsePIE);


           So here we pass the canvas id and the json data and command it to draw the PIE chart

4. Now let’s look at the code at server side, here we create one action loadData() which will be access by getReportData  [request Url  mapping path].

Here I used google json api to create the JSON object

import com.google.gson.Gson;
import com.google.gson.JsonObject;

And set the data according to Chart.js data structure.

While adding property you can see I have added one more property called title

piedata1.addProperty("title", "INDIA");


These title are nothing but the legends used for the graph.  legend.js looks for this property and display the color for particular title.

var data = [
         {
                 value: 30,
                 color:"#F38630"
         },
         {
                 value : 50,
                 color : "#E0E4CC"
         },
         {
                 value : 100,
                 color : "#69D2E7"
         }                        
]






@RequestMapping(value = "/getReportData", method = RequestMethod.GET)
       public @ResponseBody
       String loadData(HttpServletResponse response) {
                  JsonObject piedata1  = new JsonObject();
                     piedata1.addProperty("value", Integer.parseInt("30"));
                     piedata1.addProperty("color", "#F38630");
                     piedata1.addProperty("title", "INDIA");
                    
                     JsonObject piedata2  = new JsonObject();
                     piedata2.addProperty("value",  Integer.parseInt("50"));
                     piedata2.addProperty("color", "#E0E4CC");
                     piedata2.addProperty("title", "US");
                    
                     JsonObject piedata3  = new JsonObject();
                     piedata3.addProperty("value", Integer.parseInt("100"));
                     piedata3.addProperty("color", "#E0E4FF");
                     piedata3.addProperty("title", "CHINA");
                    
                     ArrayList<Object> pieDataSet = new ArrayList<Object>();
                     pieDataSet.add(piedata1);
                     pieDataSet.add(piedata2);
                     pieDataSet.add(piedata3);
                                 
                     return pieDataSet.toString();
             
       }


In this way we send the JSON response in the form of string like below and jQuery parse this string data into Json object and we get the below PIE chart as result 

 [
         {
                 value: 30,
                 color:"#F38630",
               title:”INDIA” 
         },
         {
                 value : 50,
                 color : "#E0E4CC".
               title:”US”
         },
         {
                 value : 100,
                 color : "#69D2E7"
               title:”CHINA”
         }                        
]



So only thing need to take care here is to create the json structure for graph data rest is simple.